我有一個NSTextField,我想垂直居中對齊它中的文字。基本上我需要NSTextField的答案How do I vertically center UITextField Text?如何垂直居中對齊NSTextField中的文本?
任何人都有一些指針?謝謝!
我有一個NSTextField,我想垂直居中對齊它中的文字。基本上我需要NSTextField的答案How do I vertically center UITextField Text?如何垂直居中對齊NSTextField中的文本?
任何人都有一些指針?謝謝!
你可以繼承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
然後,您可以在Interface Builder使用常規NSTextField
,並指定MDVerticallyCenteredTextFieldCell
(或任何你想命名它)作爲文本f的自定義類ield的文本字段單元格(選中文本框,暫停,然後再次單擊文本框,選擇文本字段中的單元格):
這是偉大的,除了它導致文本溢出左側和右側的文本框架框外。有任何想法嗎? – 2011-12-25 02:38:34
@ simon.d:你是......嗯。我一直在使用這段代碼(我相信它是從我在某處找到的一些蘋果示例代碼改編而來)一段時間沒有問題,但我現在意識到它只用單行(非包裝)'NSTextField's。我會再看看它,看看我是否無法在多行文本字段中工作...... – NSGod 2011-12-25 20:54:59
editWithFrame不會被調用 – 2016-09-16 16:23:50
這是更好地使用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;
}
雨燕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
}
檢查這個答案過於:http://stackoverflow.com/a/39945456/73195 – Hejazi 2016-10-09 15:49:22