iosswiftuilabelcore-text

How to get text / String from nth line of UILabel?


Is there an easy way to get (or simply display) the text from a given line in a UILabel?

My UILabel is correctly displaying my text and laying it out beautifully but occasionally I need to be able to just show certain lines but obviously I need to know how UILabel has positioned everything to do this.

I know this could easily be done with a substring but I'd need to know the start and end point of the line.

Alternatively I could scroll the UILabel if there was some kind of offset to the UILabel's frame and hide the rest of the content I didn't want to see.

I've not been able to uncover anything that shows how this could be done easily. Anyone got any good ideas?

Thanks

iphaaw


Solution

  • I don't think there's a native way for doing this (like a "takethenline" method).
    I can figure out a tricky solution but I'm not sure is the best one.
    You could split your label into an array of words.
    Then you could loop the array and check the text height until that word like this:

    NSString *texttocheck;
    float old_height = 0;
    int linenumber = 0; 
    
    for (x=0; x<[wordarray lenght]; x++) {
        texttocheck = [NSString stringWithFormat:@"%@ %@", texttocheck, [wordarray objectAtIndex:x]];
    
        float height = [text sizeWithFont:textLabel.font
                        constrainedToSize:CGSizeMake(textLabel.bounds.size.width,99999) 
                            lineBreakMode:UILineBreakModeWordWrap].height;
    
        if (old_height < height) {
            linenumber++;
        }
    }
    

    If height changes, it means there's a line break before the word.
    I can't check if the syntax is written correctly now, so you have to check it yourself.