我一直在靠墙敲打我的头,试图想出tableView:heightOfRow的理解:我想我需要帮助。我想为行内的textView执行动态行高,并且似乎无法处理该方法。我已经阅读了所有我能找到的东西,其实并不多。我可以使用此方法获取行的大小,但只有在调整表的大小时才行。不可见的行将不会被调整大小,直到它们可见并且表被调整大小。基于视图的NSTableView
我添加了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)]];
}
}
你能澄清你的疑问和/或问题吗? –
我无法按预期工作。 tableView:didAddRowView方法试图将rowView修改为正确的高度,但它最终会坐在单排高度内。 – user1804777
您是否使用自动布局 - GUI的约束? –