2

I am using NSTextField to display static text. I would like to know how much height the textfield would take for a given text and fixed width. This text field is a subview of a NSTableCellView. I return the height required by this table view cell depending upon the height required by the text field.

I am using the following way to calculate size of the text field :

- (CGSize) computeCellViewTextLabelSize:(NSString *)mesgString forWidth:(CGFloat)width {

CGSize expectedLabelSize = CGSizeMake(0, 20);

if([mesgString length] > 0) {
    NSTextField *textLabel = [[NSTextField alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    [textLabel setFont:[NSFont systemFontOfSize:13.0f]];
    [textLabel setStringValue:[NSString stringWithFormat:@"%@",mesgString]];
    NSSize size  = [((NSTextFieldCell *) [textLabel cell]) cellSizeForBounds:NSMakeRect(0, 0, width, FLT_MAX)];
    expectedLabelSize = size;
}
return expectedLabelSize; }

However there is one problem. I set the height and width of the text field as returned by this function. I have observed that the actual width of the text field is more than the width I used for calculation by 4 pixels. Hence for long messages the height calculated is more than required. This is my assumption why the height displayed is more than required.

In tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row function I am setting the width of the text field programatically

CGSize expectedLabelSize = [self computeCellViewTextLabelSize:cellView.textField.stringValue forWidth:ceil(tableViewWidth*0.6)];
            cellView.textFieldWidthConstraint.constant = expectedLabelSize.width;
            cellView.textField.preferredMaxLayoutWidth = expectedLabelSize.width;

And in the function that requests for cell height I simply use the same compute function and return height.

Can anyone suggest me the right way to calculate the height for a textfield.

hcnimkar
  • 301
  • 2
  • 13
  • Try using `NSString` `boundingRect(with size: NSSize, options: NSStringDrawingOptions = [], attributes: [String : AnyObject]? = [:]) -> NSRect` – Khundragpan Sep 02 '16 at 13:06
  • @K.Nimo I want to support from 10.9 and i guess api is available from 10.11. That won't be of much help. Can you tell my why the width of the text field increases – hcnimkar Sep 02 '16 at 13:37
  • See [NSTextFieldCell's cellSizeForBounds: doesn't match wrapping behavior?](http://stackoverflow.com/questions/35356225/nstextfieldcells-cellsizeforbounds-doesnt-match-wrapping-behavior) and [NSTableView Row Height based on NSStrings](http://stackoverflow.com/questions/3212279/nstableview-row-height-based-on-nsstrings/3214834) – CRD Sep 04 '16 at 15:53

0 Answers0