如何在NSSearchField上添加阴影

时间:2012-12-27 02:05:05

标签: macos shadow nssearchfield

我想覆盖NSSearchField类并使它看起来像 enter image description here

我查看了Apple的文档,发现NSSearchField继承自NSTextField,它继承自NSControl,NSControl本身继承自NSView。

因此,NSTextField可能对应于setShadow:方法,但是,我试图在NSSearchField实例上设置NSShadow,但实际上没有任何事情发生。

有人能说出如何获得阴影效果吗?感谢〜

1 个答案:

答案 0 :(得分:2)

NSTextField with NSShadow

// Modify theTextField so that its NSShadow will be visible.
theTextField.wantsLayer = YES ;
theTextField.bezeled = NO ;
theTextField.drawsBackground = NO ;

NSShadow* redShadow = [NSShadow new] ;
redShadow.shadowOffset = NSMakeSize(2, 2) ;
redShadow.shadowColor = [NSColor redColor] ;
theTextField.shadow = redShadow ;

结果是:Grey text, red shadow

根据我对NSShadows和NSTextFields / NSSearchFields的经验,除非NSTextField没有被标记并且没有绘制其背景,否则阴影不会出现,并且闪烁的光标会与之前的文本一起被遮挡。

编辑:

子类NSSearchField,覆盖drawRect:

- (void) drawRect:(NSRect)dirtyRect {
    NSShadow* redShadow = [NSShadow new] ;
    redShadow.shadowOffset = NSMakeSize(2, -2) ;
    redShadow.shadowColor = [NSColor redColor] ;

    [NSGraphicsContext saveGraphicsState] ;
    self.wantsLayer = YES ;     // or NO
    [redShadow set] ;
    [super drawRect:dirtyRect] ;
    [NSGraphicsContext restoreGraphicsState] ;
}

结果是:wantsLayer = YES wantsLayer = NO。 我假设您不希望放大镜图标或X按钮有阴影,所以您可以:

在原始

后添加第二个NSSearchField

在Interface Builder中这可能会更容易,但这里的代码可以在NSSearchField子类中实现。

- (void) awakeFromNib {
    [super awakeFromNib] ;

    NSSearchField* shadowSearchField = [NSSearchField new] ;
    [self.superview addSubview:shadowSearchField  positioned:NSWindowBelow  relativeTo:self ] ;
    shadowSearchField.translatesAutoresizingMaskIntoConstraints = NO ;
    shadowSearchField.editable = NO ;

    float horizontalOffset = -2 ;
    float verticalOffset   = -2 ;
    [self.superview addConstraint: [NSLayoutConstraint constraintWithItem:self  attribute:NSLayoutAttributeLeading  relatedBy:NSLayoutRelationEqual  toItem:shadowSearchField  attribute:NSLayoutAttributeLeading  multiplier:1  constant:horizontalOffset ] ] ;
    [self.superview addConstraint: [NSLayoutConstraint constraintWithItem:self  attribute:NSLayoutAttributeTop      relatedBy:NSLayoutRelationEqual  toItem:shadowSearchField  attribute:NSLayoutAttributeTop      multiplier:1  constant:verticalOffset ] ] ;
    [self.superview addConstraint: [NSLayoutConstraint constraintWithItem:self  attribute:NSLayoutAttributeWidth    relatedBy:NSLayoutRelationEqual  toItem:shadowSearchField  attribute:NSLayoutAttributeWidth    multiplier:1  constant:0 ] ] ;
    [self.superview addConstraint: [NSLayoutConstraint constraintWithItem:self  attribute:NSLayoutAttributeHeight   relatedBy:NSLayoutRelationEqual  toItem:shadowSearchField  attribute:NSLayoutAttributeHeight   multiplier:1  constant:0 ] ] ;
}

如果您可以调整第二个NSSearchField的位置和颜色,则会导致:with focusRingwithout focusRing,它们看起来最接近您想要的。