Вертикальное выравнивание текста в строке NSTableView
У меня небольшая проблема с NSTableView. Когда я увеличиваю высоту строки в таблице, текст в ней выравнивается в верхней части строки, но я хочу выровнять по вертикали по центру!
Может ли кто-нибудь предложить мне любой способ сделать это?
Спасибо,
Miraaj
Ответы
Ответ 1
Это простое решение для кода, которое показывает подкласс, который вы можете использовать для выравнивания по центру TextFieldCell.
заголовок
#import <Cocoa/Cocoa.h>
@interface MiddleAlignedTextFieldCell : NSTextFieldCell {
}
@end
код
@implementation MiddleAlignedTextFieldCell
- (NSRect)titleRectForBounds:(NSRect)theRect {
NSRect titleFrame = [super titleRectForBounds:theRect];
NSSize titleSize = [[self attributedStringValue] size];
titleFrame.origin.y = theRect.origin.y - .5 + (theRect.size.height - titleSize.height) / 2.0;
return titleFrame;
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSRect titleRect = [self titleRectForBounds:cellFrame];
[[self attributedStringValue] drawInRect:titleRect];
}
@end
Эта запись в блоге показывает альтернативное решение, которое также хорошо работает.
Ответ 2
Вот версия Swift для построения кода в ответ выше:
import Foundation
import Cocoa
class VerticallyCenteredTextField : NSTextFieldCell
{
override func titleRectForBounds(theRect: NSRect) -> NSRect
{
var titleFrame = super.titleRectForBounds(theRect)
var titleSize = self.attributedStringValue.size
titleFrame.origin.y = theRect.origin.y - 1.0 + (theRect.size.height - titleSize.height) / 2.0
return titleFrame
}
override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView)
{
var titleRect = self.titleRectForBounds(cellFrame)
self.attributedStringValue.drawInRect(titleRect)
}
}
Затем я устанавливаю высоту tableView heightOfRow в NSTableView:
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat
{
return 30
}
Установите для класса NSTextFieldCell значение VerticalCenteredTextField:
![enter image description here]()
и высота TableViewCell
![enter image description here]()
![enter image description here]()
Спасибо Брайан за вашу помощь.
Ответ 3
@iphaaw ответ обновлен для Swift 4 (заметьте, я также добавил "Cell" в конце имени класса для ясности, что также должно соответствовать имени класса в Interface Builder):
import Foundation
import Cocoa
class VerticallyCenteredTextFieldCell : NSTextFieldCell {
override func titleRect(forBounds theRect: NSRect) -> NSRect {
var titleFrame = super.titleRect(forBounds: theRect)
let titleSize = self.attributedStringValue.size
titleFrame.origin.y = theRect.origin.y - 1.0 + (theRect.size.height - titleSize().height) / 2.0
return titleFrame
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
let titleRect = self.titleRect(forBounds: cellFrame)
self.attributedStringValue.draw(in: titleRect)
}
}