2010-01-20 104 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'的大小來代替。 – 2010-01-20 20:50:47

8

下面是代碼大樓上面的答案雨燕版本:

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

感謝布萊恩您的幫助高度。

0

@ iphaaw的回答更新的雨燕4(注意,我還添加了「細胞」的類名清晰,這也需要匹配在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) 
    } 
}