NSTextFieldCell的cellSizeForBounds:不匹配包装行为? [英] NSTextFieldCell's cellSizeForBounds: doesn't match wrapping behavior?

查看:259
本文介绍了NSTextFieldCell的cellSizeForBounds:不匹配包装行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是

It seems to be commonly accepted that cellSizeForBounds: allows one to calculate a text field's "natural" size. However, for NSTextField, I've found that it doesn't quite match:

@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

,但原则是一样的。这个问题不会发生在每个字符串,但它很容易重现。)

(Note that I'm not using Auto Layout, but the principle is the same. This problem doesn't happen with every string, but it is pretty easy to reproduce.)

我怀疑这是因为文本字段的边框,这增加了额外的偏移量。有没有办法自动计算 cellSizeForBounds:和NSTextField的框架之间的关系?

I suspect this is because of the text field's border, which adds an extra offset. Is there any way to automatically compute the relationship between cellSizeForBounds: and the NSTextField's frame? How else might I solve this issue?

推荐答案

单元格大小和框架大小之间有区别。确定它的最好方法是使用 -sizeToFit 请求文本字段将其内容调整为其内容,然后将其单元格大小与其框架大小进行比较。您可能希望使用辅助屏幕外文本字段来执行此操作。请确保将其所有参数配置为与要调整大小的文本字段相同。此外,单元格大小将是精确拟合,这意味着它可能具有分数宽度或高度。由 -sizeToFit 生成的框架大小将是整数。因此,在比较框架大小以计算边框大小之前,应该将 ceil()应用于单元格大小组件。

There is a difference between the cell size and the frame size. The best way to determine it is to ask a text field to size itself to its content using -sizeToFit and then compare its cell size to its frame size. You may want to do this with a secondary, off-screen text field. Be sure to configure all of its parameters identically to the text field you're intending to resize. Also, the cell size will be an "exact" fit, meaning it will potentially have fractional width or height. The frame size resulting from -sizeToFit will be integral. So, you should apply ceil() to the cell size components before comparing to the frame size to compute the border size.

理论上,您只需为给定的文本字段配置/样式执行此操作。

In theory, you only have to do this once for a given text field configuration / style.

这篇关于NSTextFieldCell的cellSizeForBounds:不匹配包装行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆