Search code examples
iphonecocoa-touchios4uitextviewios-4.2

iPhone : How to obtain the number of lines entered in textView without consideration of width


In my iPhone app, I have a textview where in the user will input multi-line data.

Now I need a solution where I can get the number of lines.

I need a solution which does not have consideration of width.

I need only number of lines entered by user in textView.

How can I do so?


Solution

  • Since you said "without consideration of width" and not "without consideration of height", this is how you do it:

    int numberOfLines = yourUITextView.contentSize.height / yourUITextView.font.lineHeight
    

    The UIFont property lineHeight is new from iOS4.0, for older versions use leading property.

    Edit,

    this answer applies to text views where there have been automatically inserted line breaks (i.e. the line got to long), if you only want to know the number of manually inserted line breaks, Terentes answer would do it.

    To count manually inserted line breaks, this hack should do it:

    int numberOfManuallyBreaks = [[yourUITextView componentsSeparatedByString:@"\n"] count];