简体   繁体   English

Xcode 无法识别 NSLabel

[英]Xcode doesn't recognize NSLabel

I'm trying to create a NSLabel for my osx app however Xcode is not recognizing the type "NSLabel" as valid and is suggesting I try "NSPanel" instead.我正在尝试为我的 osx 应用程序创建一个 NSLabel,但是 Xcode 没有将“NSLabel”类型识别为有效,并建议我尝试使用“NSPanel”代替。

In the header file I have the following imports:在头文件中,我有以下导入:

#import <Cocoa/Cocoa.h>
#import <AppKit/AppKit.h>

How do I fix this?我该如何解决这个问题? Is there another file I need to import?我需要导入另一个文件吗?

There is no label class ( NSLabel ) on OS X. You have to use NSTextField instead, remove the bezel and make it non editable: OS X 上没有标签类 ( NSLabel )。您必须改用NSTextField ,移除边框并使其不可编辑:

[textField setBezeled:NO];
[textField setDrawsBackground:NO];
[textField setEditable:NO];
[textField setSelectable:NO];

Swift 4.2 🔸斯威夫特 4.2 🔸

open class NSLabel: NSTextField {
    override init(frame frameRect: NSRect) {
      super.init(frame: frameRect)
      self.isBezeled = false
      self.drawsBackground = false
      self.isEditable = false
      self.isSelectable = false
    }
}

I had the same question, following DrummerB advice I created this NSLabel class.我有同样的问题,按照 DrummerB 的建议,我创建了这个NSLabel类。

Header标题

//
//  NSLabel.h
//
//  Created by Axel Guilmin on 11/5/14.
//

#import <AppKit/AppKit.h>

@interface NSLabel : NSTextField

@property (nonatomic, assign) CGFloat fontSize;
@property (nonatomic, strong) NSString *text;

@end

Implementation实施

//
//  NSLabel.m
//
//  Created by Axel Guilmin on 11/5/14.
//

#import "NSLabel.h"

@implementation NSLabel

#pragma mark INIT
- (instancetype)init {
    self = [super init];
    if (self) {
        [self textFieldToLabel];
    }
    return self;
}

- (instancetype)initWithFrame:(NSRect)frameRect {
    self = [super initWithFrame:frameRect];
    if (self) {
        [self textFieldToLabel];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self textFieldToLabel];
    }
    return self;
}

#pragma mark SETTER
- (void)setFontSize:(CGFloat)fontSize {
    super.font = [NSFont fontWithName:self.font.fontName size:fontSize];
}

- (void)setText:(NSString *)text {
    [super setStringValue:text];
}

#pragma mark GETTER
- (CGFloat)fontSize {
    return super.font.pointSize;
}

- (NSString*)text {
    return [super stringValue];
}
 
#pragma mark - PRIVATE
- (void)textFieldToLabel {
    super.bezeled = NO;
    super.drawsBackground = NO;
    super.editable = NO;
    super.selectable = YES;
}

@end

You'll need to #import "NSLabel.h" to use it, but I think it's more clean.你需要#import "NSLabel.h"才能使用它,但我认为它更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM