Xcode doesn't recognize NSLabel

六月ゝ 毕业季﹏ 提交于 2019-12-10 01:16:02

问题


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.

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?


回答1:


There is no label class (NSLabel) on OS X. You have to use NSTextField instead, remove the bezel and make it non editable:

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



回答2:


I had the same question, following DrummerB advice I created this NSLabel class.

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.




回答3:


Swift 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
    }
}


来源:https://stackoverflow.com/questions/20169298/xcode-doesnt-recognize-nslabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!