Как выровнять текст по центру в NSTextField - PullRequest
11 голосов
/ 24 декабря 2011

У меня есть NSTextField, и я хочу выровнять текст по центру по вертикали.В основном мне нужен ответ NSTextField Как мне вертикально отцентрировать текст UITextField?

Кто-нибудь получил несколько указателей?Спасибо!

Ответы [ 3 ]

18 голосов
/ 24 декабря 2011

Вы можете создать подкласс NSTextFieldCell, чтобы делать то, что вы хотите:

MDVerticallyCenteredTextFieldCell.h:

#import <Cocoa/Cocoa.h>

@interface MDVerticallyCenteredTextFieldCell : NSTextFieldCell {

}

@end

MDVerticallyCenteredTextFieldCell.m:

#import "MDVerticallyCenteredTextFieldCell.h"

@implementation MDVerticallyCenteredTextFieldCell

- (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);
}

- (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

Затем вы можете использовать обычный NSTextField в Интерфейсном Разработчике и указать MDVerticallyCenteredTextFieldCell (или как вы хотите его назвать) в качестве пользовательского класса для ячейки текстового поля текстового поля (выберите текстовое поле, приостановите, затем нажмите текстовое поле еще раз, чтобы выбрать ячейку внутри текстового поля):

enter image description here

4 голосов
/ 03 августа 2017

Версия Swift 3.0 (создание пользовательского подкласса для NSTextFieldCell):

override func drawingRect(forBounds rect: NSRect) -> NSRect {
    var newRect = super.drawingRect(forBounds: rect)
    let textSize = self.cellSize(forBounds: rect)
    let heightDelta = newRect.size.height - textSize.height
    if heightDelta > 0 {
        newRect.size.height -= heightDelta
        newRect.origin.y += (heightDelta / 2)
    }
    return newRect
}
2 голосов
/ 15 апреля 2015

Лучше использовать boundingRectForFont и функцию ceilf() при расчете возможной максимальной высоты шрифта, потому что вышеупомянутое решение приводит к обрезанию текста ниже базовой линии. Так что adjustedFrameToVerticallyCenterText: будет выглядеть так

- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)rect {
    CGFloat fontSize = self.font.boundingRectForFont.size.height;
    NSInteger offset = floor((NSHeight(rect) - ceilf(fontSize))/2);
    NSRect centeredRect = NSInsetRect(rect, 0, offset);
    return centeredRect;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...