有没有办法使用约束自动调整 NSTokenField 的高度(保持宽度不变)?
-sizeToFit
应该工作,但它没有。如果我设置一个约束以保持宽度不变并调用此方法,它会忽略约束并仅调整宽度(当我想要仅调整高度时)。
有没有办法使用约束自动调整 NSTokenField 的高度(保持宽度不变)?
-sizeToFit
应该工作,但它没有。如果我设置一个约束以保持宽度不变并调用此方法,它会忽略约束并仅调整宽度(当我想要仅调整高度时)。
基于如何让 NSTextField 与自动布局中的文本一起增长?
也不要设置大小限制,顺其自然。
intrinsicContentSize
中的方法NSView
返回视图本身认为的内在内容大小。
NSTextField
计算此值时不考虑wraps
其单元格的属性,因此如果布局在单行上,它将报告文本的尺寸。
因此,自定义子类NSTokenField
可以覆盖此方法以返回更好的值,例如单元格cellSizeForBounds:
方法提供的值:
-(NSSize)intrinsicContentSize
{
if ( ![self.cell wraps] ) {
return [super intrinsicContentSize];
}
NSRect frame = [self frame];
CGFloat width = frame.size.width;
// Make the frame very high, while keeping the width
frame.size.height = CGFLOAT_MAX;
// Calculate new height within the frame
// with practically infinite height.
CGFloat height = [self.cell cellSizeForBounds: frame].height;
return NSMakeSize(width, height);
}
cellSizeForBounds
令牌字段的方法确实返回正确的大小,因此您可以像这样实现它(自定义子类,在 Swift 中):
class TagsTokenField: NSTokenField {
override func textDidChange(notification: NSNotification) {
super.textDidChange(notification)
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: NSSize {
let size = self.cell!.cellSizeForBounds(NSMakeRect(0, 0, self.bounds.size.width, 1000))
return NSMakeSize(CGFloat(FLT_MAX), size.height)
}
}