target-c: добавить вид в окно по нажатию кнопки - PullRequest
2 голосов
/ 11 декабря 2010

Я новичок в объективе-c, так что терпите меня.Это кажется довольно простым, но я, должно быть, делаю что-то не так.В IB я создал объект под названием AppController, а затем добавил действие под названием makeView и два IBOutlets, btnMakeView и mainWin, затем правильно соединил все и написал файл класса из этого.

В AppController.h у меня есть этот код:

#import <Cocoa/Cocoa.h>
@interface AppController : NSObject {
    IBOutlet NSWindow * mainWin;
    IBOutlet id btnMakeView;
}
- (IBAction)makeView:(id)sender;
@end

в AppController.m этот код:

#import "AppController.h"
#import "ViewController.h"
@implementation AppController
- (IBAction)makeView:(id)sender {

    //declare a new instance of viewcontroller, which inherits fromNSView, were going to allocate it with 
    //a frame and set the bounds of that frame using NSMakeRect and the floats we plug in.
    ViewController* testbox = [[ViewController alloc]initWithFrame:NSMakeRect(10.0, 10.0, 100.0, 20.0)];

    //this tells the window to add our subview testbox to it's contentview
    [[mainWin contentView]addSubview:testbox];
}
-(BOOL)isFlipped {
    return YES;
}
@end

в ViewController.h У меня есть этот код:

#import <Cocoa/Cocoa.h>
@interface ViewController : NSView {
}
@end

и, наконец, в ViewController.m У меня есть этот код:

#import "ViewController.h"

@implementation ViewController    
- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)rect {
    // Drawing code here.

    //sets the background color of the view object
    [[NSColor redColor]set];

    //fills the bounds of the view object with the background color
    NSRectFill([self bounds]);
}

@end

Он компилируется нормально, нет ошибок, но не получаю объект, который я предполагаю, будетпрямоугольник, начиная с x, y 10/10 и 100x20.Что я делаю не так?

1 Ответ

5 голосов
/ 11 декабря 2010

Обозначает ли mainWin действительное окно?Помимо этого, ваш код работает, хотя он может использовать некоторые улучшения.Например,

  • ViewController - это представление, а не контроллер, поэтому его не следует называть контроллером.
  • У вас есть утечка памяти.Вы никогда не выпускаете ViewController, который вы создаете. правила управления памятью очень просты ;прочтите их.

Попробуйте следующие изменения.Сначала переименуйте ViewController в RedView (или SolidColorView или что-то подобное).Вы можете сделать это очень просто: рефакторинг : щелкните правой кнопкой мыши имя класса в объявлении @interface или @implementation и выберите «Refactor ...».

В RedView.m:

- (id)initWithFrame:(NSRect)frame {
    // the idiom is to call super's init method and test self all in the
    // same line. Note the extra parentheses around the expression. This is a 
    // hint that we really want the assignment and not an equality comparison.
    if ((self = [super initWithFrame:frame])) {
        // Initialization code here.
    }
    return self;
}

В AppController.m:

- (IBAction)makeView:(id)sender {
    //declare a new instance of viewcontroller, which inherits fromNSView, were going to allocate it with 
    //a frame and set the bounds of that frame using NSMakeRect and the floats we plug in.
    RedView* testbox = [[RedView alloc] initWithFrame:NSMakeRect(10.0, 10.0, 100.0, 20.0)];

    //this tells the window to add our subview testbox to it's contentview
    // You don't need to keep a reference to the main window. The application already
    // does this. You might forget to hook up mainWin, but the following won't fail
    // as long as the app has a main window.
    [[[[NSApplication sharedApplication] mainWindow] contentView] addSubview:testbox];
    // We're done with testbox, so release it.
    [testbox release];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...