1

有没有办法使用约束自动调整 NSTokenField 的高度(保持宽度不变)?

-sizeToFit应该工作,但它没有。如果我设置一个约束以保持宽度不变并调用此方法,它会忽略约束并仅调整宽度(当我想要仅调整高度时)。

4

2 回答 2

1

基于如何让 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);
}
于 2014-05-09T01:44:48.327 回答
1

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)
    }

}
于 2015-09-20T11:26:14.510 回答