我一直在拼命试图想出对 tableView:heightOfRow: 的理解,我想我需要帮助。我想为行内的 textView 做动态行高,但似乎无法掌握这种方法。我已经阅读了我能找到的所有内容,实际上并不多。我可以使用这种方法来调整行的大小,但前提是要调整表的大小。不在视图中的行在可见并且调整表格大小之前不会正确调整大小。
我添加了 tableView:didAddRowView:forRow 方法,并使用相同的基本思想,最终将行大小压缩为一行。与 tableView:heightOfRow: 完全不同,即使它是相同的代码。我猜想设置 textView 边界的 tableView:didAddRowView:forRow 方法会以某种方式被缩放。
这是我的(希望是相关的)代码:
- (CGFloat)tableView:(NSTableView *)tv heightOfRow:(NSInteger)row {
if (tv == dataTableView) {
NSInteger valueCol = [tv columnWithIdentifier:@"value"];
NSTableCellView *valueView = [tv viewAtColumn:valueCol row:row makeIfNecessary:NO];
if (valueView) {
// Working on the interesting column and this row is visible
NSRect bounds = [[valueView textField] bounds];
id value = [[valueView textField] stringValue];
NSFont *fieldFont = [[valueView textField] font];
CGFloat adjustedHeight = [value heightForWidth:bounds.size.width font:fieldFont];
CGFloat rowHeight = [tv rowHeight];
if (adjustedHeight <= rowHeight) adjustedHeight = rowHeight;
return adjustedHeight;
}
}
return [tv rowHeight];
}
- (void)tableView:(NSTableView *)tv didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row {
if (tv == dataTableView) {
NSInteger valueCol = [tv columnWithIdentifier:@"value"];
NSTableCellView *colView = [rowView viewAtColumn:valueCol];
NSRect textFieldViewBounds = [[colView textField] bounds];
NSTextField *colTextField = [colView textField];
NSFont *colFont = [colTextField font];
id value = [colTextField stringValue];
CGFloat newHeight = [value heightForWidth:textFieldViewBounds.size.width font:colFont];
NSSize colViewSize = colView.bounds.size;
colViewSize.height = newHeight;
textFieldViewBounds.size.height = newHeight;
[colTextField setBounds:textFieldViewBounds];
}
}
更新:新代码运行得更好,但在初始加载时仍然存在故障,有时在滚动时:
- (CGFloat)tableView:(NSTableView *)tv heightOfRow:(NSInteger)row {
if (tv == dataTableView) {
NSInteger valueCol = [tv columnWithIdentifier:@"value"];
NSTableCellView *valueView = [tv viewAtColumn:valueCol row:row makeIfNecessary:NO];
if (valueView) {
// Working on the interesting column
NSRect bounds = [[valueView textField] bounds];
id value = [[valueView textField] stringValue];
NSFont *fieldFont = [[valueView textField] font];
CGFloat adjustedHeight = [value heightForWidth:bounds.size.width font:fieldFont];
CGFloat rowHeight = [tv rowHeight];
if (adjustedHeight <= rowHeight) adjustedHeight = rowHeight;
return adjustedHeight;
}
}
return [tv rowHeight];
}
- (void) tableView:(NSTableView *)tv didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row {
if (tv == dataTableView) {
[dataTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(row, 1)]];
}
}