2011-12-24 28 views

Respuesta

18

Usted podría subclase NSTextFieldCell a hacer lo que quiera:

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 

A continuación, puede utilizar un habitual NSTextField en Interface Builder y especifique MDVerticallyCenteredTextFieldCell (o lo que sea que quiera nombrar) como la clase personalizada para el texto f celda de campo de texto de ield (seleccione el campo de texto, hacer una pausa, a continuación, haga clic en el campo de texto de nuevo para seleccionar la celda dentro del campo de texto):

enter image description here

+0

esto es genial, excepto que está causando que el texto se derrame fuera del marco del campo de texto en los lados izquierdo y derecho. ¿algunas ideas? –

+0

@ simon.d: está bien ... Hmm. He estado usando este código (que creo que está adaptado de un código de ejemplo de Apple que encontré en algún lugar) por un tiempo sin problemas, aunque me doy cuenta ahora de que era solo con 'NSTextField's de una sola línea (sin envoltorio). Volveré a echarle un vistazo para ver si no puedo hacer que funcione para campos de texto de varias líneas ... – NSGod

+0

editWithFrame no se llama –

2

Es mejor utilizar boundingRectForFont y la función ceilf() en el cálculo de la posible altura máxima de la fuente , porque la solución mencionada hace que el texto se corte en la línea de base. Por lo que el adjustedFrameToVerticallyCenterText: se verá como esta versión

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

Swift 3.0 (Crear una subclase personalizada para 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 
} 
Cuestiones relacionadas