允许计算文本字段的“自然”大小似乎已被普遍 接受。cellSizeForBounds:
但是,对于 NSTextField,我发现它不太匹配:
@interface MyTextField : NSTextField @end
@implementation MyTextField
- (void)textDidChange:(NSNotification *)notification {
[super textDidChange:notification];
[self validateEditing]; // Forces updating from the field editor
NSSize cellSize = [self.cell cellSizeForBounds:
NSMakeRect(0, 0, self.bounds.size.width, CGFLOAT_MAX)];
NSRect frame = self.frame;
CGFloat heightDelta = cellSize.height - frame.size.height;
frame.size.height += heightDelta;
if (!self.superview.flipped) { frame.origin.y -= heightDelta; }
self.frame = frame;
}
@end
(请注意,我没有使用 Auto Layout,但原理是一样的。这个问题不会发生在每个字符串上,但很容易重现。)
我怀疑这是因为文本字段的边框增加了额外的偏移量。有没有办法自动计算cellSizeForBounds:
和 NSTextField之间的关系frame
?我还能如何解决这个问题?