2010-01-20 3 views
11

У меня небольшая проблема с NSTableView. Когда я увеличиваю высоту строки в таблице, текст в ней выравнивается в верхней части строки, но я хочу выровнять по вертикали по центру!вертикально выравнивающий текст в строке NSTableView

Может ли кто-нибудь предложить мне любой способ это сделать?

Спасибо,

Miraaj

ответ

20

Это простой код решение, которое показывает подкласс можно использовать для выравнивания средней 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 

This blog entry показывает альтернативное решение, которое также хорошо работает.

+1

'размер 'принимает бесконечную ширину - он не учитывает перенос строк. Я предлагаю 'boundingRectForSize: options:', с размером от 'cellFrame', вместо этого. –

8

Вот 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 быть VerticallyCenteredTextField:

enter image description here

и высота TableViewCell

enter image description here

enter image description here

Спасибо Bryan за вашу помощь.

0

@ 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) 
    } 
} 
Смежные вопросы