NSTextField透明背景

时间:2012-06-20 13:25:21

标签: macos cocoa nstextfield

我创建透明 NSTextField

self.myTextField = [[NSTextField alloc] initWithFrame:CGRectMake(backgroundView.frame.origin.x + backgroundView.frame.size.width + 20, self.projectTitle.frame.origin.y - 30.0, 100, 20)];
self.myTextField.editable = NO;
self.myTextField.bezeled = NO;
self.myTextField.drawsBackground = YES;
self.myTextField.backgroundColor = [NSColor clearColor];
self.myTextField.selectable = NO;
self.myTextField.font = [NSFont fontWithName:@"Helvetica Neue" size:16];

    [self addSubview:self.compressingTime];

结果文字看起来很糟糕。 enter image description here 如果我设置背景颜色

    self.myTextField.backgroundColor = [NSColor colorWithCalibratedRed:0.85 green:0.85 blue:0.85 alpha:1.0];

一切看起来都不错enter image description here 我也试过drawsBackground = NO;你们知道如何解决这个问题吗?

9 个答案:

答案 0 :(得分:59)

秘诀是在NSTextField ...

上设置所有这三个属性
myTextField.bezeled         = NO;
myTextField.editable        = NO;
myTextField.drawsBackground = NO;

答案 1 :(得分:12)

.xib文件中有一个属性,位于属性检查器

下文本字段的界面构建器窗口中
  1. 检查显示绘制背景
  2. 选择背景颜色。为透明背景选择清晰的颜色。
  3. enter image description here

答案 2 :(得分:4)

从10.12开始,您可以这样做:

Uncaught TypeError: Cannot read property 'replace' of undefined

答案 3 :(得分:0)

我最终使用CATextLayer代替NSTextField

答案 4 :(得分:0)

也来这里找这个,并且有给我透明灰色的背景。关键是没有挡板。我的代码如下:

NSTextField *yourLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, width , height * 1.0/3.0)];
yourLabel.editable = false;
yourLabel.bezeled = false;
[yourLabel setTextColor:[NSColor blackColor]];
[yourLabel setBackgroundColor:[NSColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.1]];

为了完整起见,我较早地获得了宽度和高度,因为它们被多次用于布局:

height = self.window.frame.size.height;
width = self.window.frame.size.width;

答案 5 :(得分:0)

我有同样的问题。默认外观为空。我尝试设置暗模式,它可以正常工作。

self.nameTextField.appearance = [NSAppearance appearanceNamed:NSAppearanceNameVibrantDark];

答案 6 :(得分:-1)

您无需切换到CATextLayer即可有效地告诉您的应用程序为文本字段使用图层。您可以改为使用它:

textField.drawsBackground = NO;
textField.wantsLayer      = YES;

答案 7 :(得分:-2)

我刚才遇到了这个问题。我通过从NSTextField的超级视图中删除名为backgroundColor 的属性来修复它。

我正在使用backgroundColor作为NSView子类上CALayer属性的便捷getter / setter。尽管在NSView上没有记录此属性,但看起来我不小心覆盖了NSView上的属性。

Yay for subclassing!

答案 8 :(得分:-3)

清晰的颜色会使当前视图(即)NSTextView的背景变为透明,因此可以看到保存NSTextView的NSView的颜色。

相关问题