我正在尝试实现一个自定义NSTextField
a)在激活时改变颜色,b)在左上角有一个标签。
我有以下实现:
在TestTextField.h
@interface TestTextField : NSTextField
- (id)initFullWidthWithLabel:(NSString *)label andPreset:(NSString *)preset;
...
@end
在TestTextField.m
@interface TestTextField() {
BOOL _thisFieldIsActive;
}
@property (nonatomic, strong) NSTextField *label;
@end
@implementation TestTextField
- (id)initFullWidthWithLabel:(NSString *)label andPreset:(NSString *)preset {
self = [super initWithFrame:NSZeroRect];
if (self) {
_thisFieldIsActive = NO;
[self setFocusRingType:NSFocusRingTypeNone];
// small label top left
_label = [[NSTextField alloc] initWithFrame:NSZeroRect];
_label.stringValue = label;
if (preset) {
self.stringValue = preset;
}
else {
self.stringValue = @"0";
}
[self layoutUI];
}
return self;
}
- (void)turnActiveOff {
[self toggleActive:NO];
}
- (void)toggleActive:(BOOL)active {
_thisFieldIsActive = active;
if (_thisFieldIsActive) {
self.backgroundColor = [NSColor blueColor];
self.textColor = [NSColor whiteColor];
_label.textColor = [NSColor whiteColor];
}
else {
self.backgroundColor = [NSColor clearColor];
self.textColor = [NSColor blackColor];
_label.textColor = [NSColor grayColor];
}
}
- (BOOL)becomeFirstResponder {
NSLog(@"BecomeFirstResponder");
[self selectText:self];
[self toggleActive:YES];
return [super becomeFirstResponder];
}
- (void)textDidEndEditing:(NSNotification *)notification {
NSLog(@"DidEndEditing");
[self toggleActive:NO];
[super textDidEndEditing:notification];
}
- (void)layoutUI {
self.alignment = NSRightTextAlignment;
self.font = [NSFont fontWithName:@"HelveticaNeue-Light" size:32.0f];
self.layer.borderColor = [NSColor whiteColor].CGColor;
self.layer.borderWidth = 1.0f;
[self.layer setCornerRadius:4.0f];
// small label top left
_label.font = [NSFont fontWithName:@"HelveticaNeue-Light" size:12.0f];
_label.alignment = NSLeftTextAlignment;
_label.textColor = [NSColor grayColor];
_label.stringValue = [_label.stringValue uppercaseString];
_label.selectable = NO;
_label.editable = NO;
_label.drawsBackground = NO;
_label.bezeled = NO;
[self addSubview:_label];
NSDictionary *metrics = @{@"borderPadding": @5};
_label.translatesAutoresizingMaskIntoConstraints = NO;
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(borderPadding)-[_label(100)]" options:0 metrics:metrics views:@{ @"_label" : _label }]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(borderPadding)-[_label(30)]" options:0 metrics:metrics views:@{ @"_label" : _label }]];
}
在我的ViewController中,我只需调用自定义initFullWidthWithLabel:andPreset:
方法并将其作为子视图添加到VC view
我可以看到标签定位正确,但是一旦字段变为活动状态并且设置了backgroundColor,它似乎就会掩盖标签。如何确保标签保持在最顶层? 即使关闭了backgorund着色,标签仍然是隐藏的。
由于
答案 0 :(得分:0)
解决方案的核心是使用自定义子类NSTextFieldCell
和一种方法:
- (NSRect)drawingRectForBounds:(NSRect)rect {
NSRect rectInset = NSMakeRect(rect.origin.x + 100.0f, rect.origin.y, rect.size.width - 100.0f, rect.size.height);
return [super drawingRectForBounds:rectInset];
}