What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

后端 未结 4 1654
难免孤独
难免孤独 2020-11-28 22:51

In my question \"How do I get -[NSString sizeWithFont:forWidth:lineBreakMode:] to work?\", I learned that -[NSString sizeWithFont:constrainedToSize:lineBreakMode:]

4条回答
  •  既然无缘
    2020-11-28 23:20

    For a while I thought this routine was simply broken. It sounds like it's the perfect routine for working out how high a piece of text is, when wrapped at a certain width. However this is not what it does. Indeed, the height returned is always a single line. (Which is pointless, incidentally: UIFont's -leading returns the same value.)

    To quote the documentation at the time of writing:

    Although it computes where line breaks would occur, this method does not actually wrap the text to additional lines; [...]

    This sentence confused me for a long time. My thoughts ran along the lines of:

    • Computing line-breaks, but not wrapping. Eh?
    • Maybe they mean the receiving NSString itself won't be mutated to reflect line-breaks? But I don't expect that anyway?
    • This sentence is not consistent with itself. I have no choice but to ignore it.

    However, it turns out there's a meaning that matches the behaviour we see. It seems that what they mean is:

    This routine will compute where the first line-break will occur, and all text after this is ignored for the purposes of calculating the bounding box.

    The bounding box returned will therefore have the height of a single line and a width up to the maximum specified. (The width may be less depending on where the line-break is calculated, or if the text is short enough that it does not need the maximum width.)

    To, um, answer the actual question: What is it good for? I haven't found anything useful myself: only things where I thought it would be useful, but wasn't. Some things which spring to mind, however, are:

    • Centering a single-line piece of text. I'm thinking buttons and/or titles here. (Although UILabel and UIButton can do it, sometimes you want to draw it yourself.)
    • Calculating the bounds for an "extract" of a longer piece of text. Here I'm thinking about where you might want to show a snippet of a much larger piece of text.

提交回复
热议问题