質問

nstableviewには小さな問題があります。テーブルの列の高さが増えているとき、そのテキストは列の上部に揃っていますが、垂直に中央に配置したいです!

誰かが私にそれをする方法を提案できますか?

ありがとう、

ミラージ

役に立ちましたか?

解決

これは、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でtableview heightofrowの高さを設定します。

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

nstextfieldcellのクラスを垂直にセントレッドテキストフィールドに設定します。

enter image description here

テーブルビューセルの高さ

enter image description here

enter image description here

ブライアンの助けに感謝します。

@iphaawの回答は、Swift 4のために更新されました(Clarityのためにクラス名の最後に「Cell」も追加しました。これは、インターフェイスビルダーのクラス名を一致させる必要があります):

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