Objective c 以编程方式将文本添加到窗口

Objective c 以编程方式将文本添加到窗口,objective-c,cocoa,Objective C,Cocoa,我正在尝试在不使用Xcode的情况下,用Objective-c编写一些非常基本的Cocoa编程。这主要是为了学习,而不是为了开发真实世界的应用程序 我用以下源代码创建了一个“hello world”程序: #import <Cocoa/Cocoa.h> int main(int argc, const char * argv[]) { NSApplication* app = [NSApplication sharedApplication]; id window

我正在尝试在不使用Xcode的情况下,用Objective-c编写一些非常基本的Cocoa编程。这主要是为了学习,而不是为了开发真实世界的应用程序

我用以下源代码创建了一个“hello world”程序:

#import <Cocoa/Cocoa.h>

int main(int argc, const char * argv[]) {
    NSApplication* app = [NSApplication sharedApplication];
    id window =
         [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 400, 400)
                                            styleMask:NSWindowStyleMaskTitled
                                                 backing:NSBackingStoreBuffered
                                                   defer:NO];
    [window setTitle:@"Hello world"];
    [window makeKeyAndOrderFront:nil];
    [window center];


    NSText* t = [[NSText alloc] initWithFrame:NSMakeRect(20,20,100,100)];
    [t setString:@"test"];

    [window addSubview:t];

    [app run];

    return 0;
}

为什么我的应用程序会因
[NSWindow addSubview:]:无法识别的选择器发送到实例而崩溃?如何以编程方式将文本添加到窗口?

尝试使用NSTextField而不是NSText:

NSRect frameRect = NSMakeRect(20,20,100,100)
NSTextField *myTextField = [[NSTextField alloc] initWithFrame:frameRect];
[myView addSubView:myTextField];

此外,您需要制作基于AppDelegate的应用程序或基于故事板的应用程序,以便使用NSView显示您的对象。

来这里寻找将NSTextfield添加到视图的解决方案,但它确认了我已经尝试使用的内容。相反,我尝试使用“setContentView”,但随后文本填充了视图,而我需要它作为子视图工作。这是我的代码:

NSTextField *yourLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, width , height * 1.0/3.0)];
    yourLabel.editable = false;
    yourLabel.bezeled = true;
    [yourLabel setTextColor:[NSColor blackColor]];
    [yourLabel setBackgroundColor:[NSColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.5]];
    [yourLabel setFont:[NSFont fontWithName:@"GurmukhiMN-Bold" size:(height/24)]];
    yourLabel.stringValue = [NSString stringWithFormat:@"The Second Output Is Operational"];
    yourLabel.alignment = NSTextAlignmentCenter;
    [self.window.contentView addSubview:yourLabel];
关键的区别在于我将信息发送到哪里。似乎这是添加子视图的最佳方式,其他子视图会导致竞争条件或崩溃

为了完整性,我在前面得到了宽度和高度(它们在整个视图中都被使用,所以抓住它们一次):


你所说的基于AppDelegate的应用是什么意思?(我试着不使用故事板)它崩溃了,因为你从未创建过视图;不能将子视图添加到不存在的视图中。
NSTextField *yourLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, width , height * 1.0/3.0)];
    yourLabel.editable = false;
    yourLabel.bezeled = true;
    [yourLabel setTextColor:[NSColor blackColor]];
    [yourLabel setBackgroundColor:[NSColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.5]];
    [yourLabel setFont:[NSFont fontWithName:@"GurmukhiMN-Bold" size:(height/24)]];
    yourLabel.stringValue = [NSString stringWithFormat:@"The Second Output Is Operational"];
    yourLabel.alignment = NSTextAlignmentCenter;
    [self.window.contentView addSubview:yourLabel];
height = self.window.frame.size.height;
width = self.window.frame.size.width;