【问题标题】:How to display NSText to NSWindow?如何将 NSText 显示到 NSWindow?
【发布时间】:2022-08-03 00:21:56
【问题描述】:

我有以下代码:

#include <Cocoa/Cocoa.h>

NSColor *createColor(float r, float g, float b, float a) {
    return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
}

NSRect createRect(float startX, float startY, float width, float height) {
    return NSMakeRect(startX, startY, width, height);
}

int main() { @autoreleasepool {
        NSWindow *window = [[NSWindow alloc] init];
        window.title = @\"Title\";
        window.subtitle = @\"Subtitle\";

        NSText *label = [[NSText alloc] initWithFrame: createRect(10, 10, 20, 20)];
        t.string = @\"test\";

        [window setFrame:createRect(0, 0, 300, 300) display:YES animate:YES];
        [window setBackgroundColor: createColor(0.5, 1, 0.1, 1)];
        [window makeKeyAndOrderFront:nil];
        while (1) {
            NSEvent *event = [window nextEventMatchingMask:NSEventMaskAny];
        }
    }
}

是否有一种简单的方法可以显示到 NSWindow,例如:

[window *command*: label];

我查看了this 的帖子,但它没有解决我的问题,因为它使用的是 NSApplication 而不是 NSWindow。另外,我更喜欢使用 NSText 而不是 NSTextField。

  • 链接的问题使用NSWindowNSTextField,这是显示标签的最简单方法。看看两个答案。为什么要使用NSText 而不是NSTextFieldNSTextViewNSText 的子类怎么样?
  • 我更喜欢使用 NSText,这意味着如果绝对必要,我可以使用 NSTextField。
  • 为什么要使用NSText 而不是NSTextView

标签: objective-c nswindow


【解决方案1】:

它很简单:

[window.contentView addSubview: label];

【讨论】:

    猜你喜欢
    • 2012-11-08
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    相关资源
    最近更新 更多