Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vertically aligning text in NSTableView row

I have a small problem with NSTableView. When I am increasing height of a row in table, the text in it is aligned at top of row but I want to align it vertically centered!

Can anyone suggest me any way to do it ??

Thanks,

Miraaj

like image 957
Devarshi Avatar asked Jan 20 '10 16:01

Devarshi


People also ask

How do I vertically align text in a table cell?

To place an item at the top or bottom of its cell, insert the "VALIGN=" attribute within the code for that cell. To vertically align an entire row (e.g., placing all data in that row at the tops of the cells), insert the "VALIGN=" attribute within the code for that row.

How do I align text vertically and horizontally?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.


2 Answers

This is a simple code solution that shows a subclass you can use to middle align a TextFieldCell.

the header

#import <Cocoa/Cocoa.h>


@interface MiddleAlignedTextFieldCell : NSTextFieldCell {

}

@end

the code

@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 shows an alternative solution that also works well.

like image 185
Bryan McLemore Avatar answered Oct 01 '22 02:10

Bryan McLemore


Here is the Swift version of the code building on the answer above:

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

Then I set the height of the tableView heightOfRow in the NSTableView:

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

Set the class of the NSTextFieldCell to be VerticallyCenteredTextField:

enter image description here

and the height of the TableViewCell

enter image description here

enter image description here

Thanks Bryan for your help.

like image 22
iphaaw Avatar answered Oct 01 '22 01:10

iphaaw