I have an NSTextField and I want to vertically center align the text in it. Basically I need the NSTextField answer of How do I vertically center UITextField Text?
Anyone got some pointers? Thanks!
For example, if you're trying to align something horizontally OR vertically, it's not that difficult. You can just set text-align to center for an inline element, and margin: 0 auto would do it for a block-level element.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
Use line-height for vertical centering with a fixed height To vertically center a single line of text or an icon within its container, we can use the line-height property. This property controls the height of a line in a run of text and adds an equal amount of space above and below the line-box of inline elements.
You could subclass NSTextFieldCell
to do what you want:
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
You can then use a regular NSTextField
in Interface Builder, and specify MDVerticallyCenteredTextFieldCell
(or whatever you want to name it) as the custom class for the text field's text field cell (select the textfield, pause, then click the textfield again to select the cell inside the text field):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With