我对NSTableView有一个小问题。当我在表格中增加一行的高度时,其中的文本被排列在行的顶部,但我想将它垂直居中对齐!垂直对齐NSTableView行中的文本
任何人都可以建议我任何方式做到这一点?
感谢,
Miraaj
我对NSTableView有一个小问题。当我在表格中增加一行的高度时,其中的文本被排列在行的顶部,但我想将它垂直居中对齐!垂直对齐NSTableView行中的文本
任何人都可以建议我任何方式做到这一点?
感谢,
Miraaj
这是一个简单的代码解决方案,显示您可以使用中间对齐一个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示出了替代的解决方案,也工作得很好。
下面是代码大楼上面的答案雨燕版本:
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:
和TableViewCell
感谢布莱恩您的帮助高度。
@ 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)
}
}
'大小'假定无限宽度 - 它不考虑换行。我建议'boundingRectForSize:options:',用'cellFrame'的大小来代替。 – 2010-01-20 20:50:47