我想重写NSSearchField类,让它看起来像

我看了苹果的文档,发现NSSearchField是从NSTextField继承的,而NSControl是继承的,而NSControl本身是从NSView继承的。
因此,方法可以对应于setShadow: NSTextField,然而,我尝试在NSSearchField实例上设置一个方法,但实际上什么也没有发生。
有谁能告诉我如何获得阴影效果吗?谢谢~
发布于 2012-12-27 14:49:35
使用NSShadow的NSTextField
// 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 ;这将导致:

在我使用NSShadows和NSTextFields/NSSearchFields的经验中,阴影不会出现,除非NSTextField没有边框并且不绘制其背景,并且闪烁的光标与它前面的文本一起阴影。
编辑:
重写drawRect:的子类NSSearchField
- (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] ;
}这将导致:


。我假设你不希望放大镜图标或X按钮有阴影,所以你可以:
在原始文件后面添加第二个NSSearchField
在接口生成器中可能更容易做到这一点,但下面是在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的位置和颜色,它看起来最接近你想要的。
https://stackoverflow.com/questions/14048539
复制相似问题