我对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

此博客条目 显示出一种也很好地工作的替代解决方案。

其他提示

这是上面答案上的代码构建的迅速版本:

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)
    }
}

然后,我在nstableview中设置了桌面高度的高度:

func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat
{
    return 30
}

将nstextfieldcell的类设置为垂直感染的textfield:

enter image description here

以及桌面的高度

enter image description here

enter image description here

感谢布莱恩的帮助。

@iphaaw的答案已更新了Swift 4(请注意,我还在类名称的末尾添加了“单元格”,以确保清晰度,还需要在接口构建器中匹配类名称):

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)
    }
}

即使这是一个非常古老的问题,有一个公认的答案,这里也是一个替代解决方案:

进入IB,选择坐在nstablecellview中的Nstextfield,然后在容器中垂直添加新的“中心”约束。您还应该添加水平约束(这可能是将/尾随空间设置为0或适合您需求的任何东西)。

在NsoutlineView中使用了此功能,并像魅力一样工作。在我的情况下,性能不是问题,因为我没有很多单元格,但是我希望它不会比手动计算尺寸更糟糕。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top