NSTableView Row Height based on NSStrings

前端 未结 5 1747
失恋的感觉
失恋的感觉 2020-12-15 13:48

Basically, I have an NSTableView with 1 collumn, and I\'m inserting long strings into each row. However, not all the strings are long, so I\'d like the height of each row to

5条回答
  •  清歌不尽
    2020-12-15 14:29

    Here's a small improvement on Robert D'Almeida's answer (I originally submitted this as an edit, but it was rejected because "the original meaning or intent of the post would be lost"). I've added the method signature and made a few other small changes.

    - (CGFloat)tableView:(NSTableView *)aTableView heightOfRow:(NSInteger)row {
        CGFloat heightOfRow = 100; // or some other default value
    
        // get the content for this table cell from the model
        NSString *string = [[_tableViewDataSourceArray objectAtIndex:rowIndex] 
                                  valueForKey:@"StringToDisplay"];
    
        NSTableColumn *tableColumn = [aTableView
                                  tableColumnWithIdentifier:@"TableColumnIdentifier"];
    
        if (tableColumn) {
            NSCell *dataCell = [tableColumn dataCell];
            [dataCell setWraps:YES];
            [dataCell setStringValue:string];
    
            // See how tall it naturally would want to be if given a restricted
            // width, but unbound height
            NSRect myRect = NSMakeRect(0, 0, [tableColumn width], CGFLOAT_MAX);
            heightOfRow = [dataCell cellSizeForBounds:myRect].height;
        }
    
        return heightOfRow;
    }
    

提交回复
热议问题