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.