Search code examples
macosnsstringosx-yosemitenstableviewosx-elcapitan

How to measure multiline text height in OS X 10.11?


Problem: I want to set long text in view-based NSTableView cell where the row height is to be adjusted appropriately. For this I need to calculate the height of the text bounding rectangle. I found solution: https://discussions.apple.com/thread/4216370?tstart=0 but it uses functions deprecated in 10.11. So the fundamental question is: how to measure bounding rectangle of multiline/line-broken text while ensuring its conformance with OS X 10.11?


Solution

  • According to the header file, you should use -initWithSize: instead of -initWithContainerSize:. Not sure why that's not mentioned in the documentation. Of course, if you need to be able to run your code on versions before 10.11, then you'll have to conditionally call either -initWithSize: or -initWithContainerSize:, depending on the current version.

        NSTextContainer *container;
        if ([NSTextContainer instancesRespondToSelector:@selector(initWithSize:)]) {
            container = [[NSTextContainer alloc] initWithSize: NSMakeSize(width, FLT_MAX)];
        } else {
            container = [[NSTextContainer alloc] initWithContainerSize: NSMakeSize(width, FLT_MAX)];
        }
    

    Weirdly, I don't actually get a deprecation warning when I build a project that uses the old initializer with the 10.11 SDK.