2

我正在一个NSSearchFieldCell子类中做一些自定义绘图。但是,覆盖其两种绘图方法中的任何一种都会导致占位符文本不对齐。

例如,仅仅通过使用这个NSSearchFieldCell覆盖NSCell的绘图方法的自定义子类将导致占位符文本左对齐。

class CustomSearchFieldCell: NSSearchFieldCell {
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
    }

    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.drawInterior(withFrame: cellFrame, in: controlView)
    }
}

即使在将搜索字段的centersPlaceholder属性设置为true并且重新布局搜索字段或重置搜索字段的stringValue.

注释掉这两种方法将使占位符文本(和放大镜再次居中。

搜索字段居中对齐

然而,只有一个覆盖(即使它什么都不做,只调用它的超类的实现)会使搜索字段的占位符文本和放大镜变为左对齐。

搜索字段左对齐

问题是,如何获得center align placeholder工作并仍然拥有自定义图纸?

请注意,我需要在单元格内进行一些自定义绘图和鼠标处理,因此需要覆盖。

这是在 macOS 10.12.6 上观察到的。

4

1 回答 1

0

您应该研究此方法,因为当鼠标离开文本字段并相应地更新框架时会调用它:-

- (void)stopTracking:(NSPoint)lastPoint at:(NSPoint)stopPoint inView:(NSView *)controlView mouseIsUp:(BOOL)flag;

我需要将 NSSearchFieldCell 的文本垂直居中,下面的代码可以做到这一点,因此您可以尝试将所需的组件居中 - :

//
//  VerticallyCenteredTextFieldCell.m
//
//  Created by Vikram on 01/03/17.
//  Copyright © 2017 Vikram. All rights reserved.
//

#import "VerticallyCenteredTextFieldCell.h"

@implementation VerticallyCenteredTextFieldCell

- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)frame
{
    // super would normally draw text at the top of the cell
    NSInteger offset = floor((NSHeight(frame) -
                              ([[self font] ascender] - [[self font] descender])) / 2);
    return NSInsetRect(frame, 0.0, offset-3);
}
- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView
               editor:(NSText *)editor delegate:(id)delegate event:(NSEvent *)event
{
    [super editWithFrame:[self adjustedFrameToVerticallyCenterText:aRect]
                  inView:controlView editor:editor delegate:delegate event:event];
}
- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView
                 editor:(NSText *)editor delegate:(id)delegate
                  start:(NSInteger)start length:(NSInteger)length
{

    [super selectWithFrame:[self adjustedFrameToVerticallyCenterText:aRect]
                    inView:controlView editor:editor delegate:delegate
                     start:start length:length];
}
- (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView *)view
{
     [super drawInteriorWithFrame:
     [self adjustedFrameToVerticallyCenterText:frame] inView:view];
}

@end

我已经在objective-c中制作了它,因此请相应地阅读它并使其在swift中有用。

于 2018-02-13T10:39:21.390 回答