How to find actual number of lines of UILabel?

前端 未结 14 2409
灰色年华
灰色年华 2020-11-27 13:10

How can I find the actual number of lines of a UILabel after I have initialized it with a text and a font? I have set

14条回答
  •  忘掉有多难
    2020-11-27 13:48

    Xamarin.iOS

    Thanks to the answers everyone provided above.

    This gets number of visible lines.

    public static int VisibleLineCount(this UILabel label)
    {
        var textSize = new CGSize(label.Frame.Size.Width, nfloat.MaxValue);
        nfloat rHeight = label.SizeThatFits(textSize).Height;
        nfloat charSize = label.Font.LineHeight;
        return Convert.ToInt32(rHeight / charSize);
    }
    

    This gets actual number of lines the text will occupy on screen.

    public static int LineCount(this UILabel label)
    {
        var maxSize = new CGSize(label.Frame.Size.Width, nfloat.MaxValue);
        var charSize = label.Font.LineHeight;
        var text = (label.Text ?? "").ToNSString();
        var textSize = text.GetBoundingRect(maxSize, NSStringDrawingOptions.UsesLineFragmentOrigin, new UIStringAttributes() { Font = label.Font }, null);
        return Convert.ToInt32(textSize.Height / charSize);
    }
    

    A helper method I find useful for my use case.

    public static bool IsTextTruncated(this UILabel label)
    {
        if (label.Lines == 0)
        {
            return false;
        }
        return (label.LineCount() > label.Lines);
     }
    

    To get a more accurate line count:

    • Use font.lineHeight instead of font.pointSize
    • round() the line count after division

提交回复
热议问题