问题
I create transparent 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];
And as a result text look bad.
If I set background color self.myTextField.backgroundColor = [NSColor colorWithCalibratedRed:0.85 green:0.85 blue:0.85 alpha:1.0];
everything looks ok
I have also tried withdrawsBackground = NO;
Do you guys know how to fix this?
回答1:
The secret is setting ALL THREE of these properties on the NSTextField
...
myTextField.bezeled = NO;
myTextField.editable = NO;
myTextField.drawsBackground = NO;
回答2:
There is a property in the .xib file, on the interface builder window for the text field, under attribute inspector
- Check the Display Draws Background
- Select a background color. Select clear color for transparent background.
回答3:
As of 10.12 you can just do:
let label = NSTextField(labelWithString: "HELLO")
回答4:
I ended up using CATextLayer
instead NSTextField
.
回答5:
Came here looking for this too, and have got the background to give me a transparent grey. Key is to not have a bezel. My code below:
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]];
For completeness I had got the width and height earlier because they get used many times for layout:
height = self.window.frame.size.height;
width = self.window.frame.size.width;
回答6:
I had this problem just now. I fixed it by removing a property named backgroundColor
from the NSTextField's superview.
I was using backgroundColor
just as a convenience getter/setter for the CALayer properties on an NSView subclass. Although this property isn't documented on NSView, it looks like I had accidentally overridden a property on NSView.
Yay for subclassing! 😒
回答7:
The clear color will make the current view (ie)NSTextView's background as transparent hence the color of NSView which holds the NSTextView is visible.
来源:https://stackoverflow.com/questions/11120654/nstextfield-transparent-background