Shakesbeer
Shakesbeer

Reputation: 523

How to add a scroll function to a UILabel

In Xcode, I created a UILabel which will autoresize depending on how many lines of text I put on it. But I don't want the UILabel's height to exceed a certain limit (240 in my example), the code goes like this:

NSString *text = @"imagine this is a huge wall of text\n\n\n"
UILabel *myLabel = [[UILabel alloc] init];
[myLabel setNumberOfLines:0];
CGSize labelSize = [text sizeWithFont:myLabel.font constrainedToSize:CGSizeMake(280, 240) lineBreakMode:myLabel.lineBreakMode];
myLabel.frame = CGRectMake(0, 0, 280, labelSize.height);

This works fine when my text is within about 10-15 lines. But if I put in something like 40 lines of text, the extra lines of text will go beyond my UILabel and get cut off.

How can I add a scroll function to myLabel so that myLabel will still have a maximum height of 240, and I can simply scroll down to view those extra lines of text in myLabel?

Upvotes: 44

Views: 49235

Answers (2)

Peter Sarnowski
Peter Sarnowski

Reputation: 11970

Use UITextView (reference).

It's designed to do exactly that. Disable editing, and you get a scrollable label.

Upvotes: 133

shivangi
shivangi

Reputation: 187

You can add your UILabel on a UIScrollView Like this and can also do like this---

scrollView.backgroundColor = [UIColor clearColor];

        UILabel * label = [[UILabel alloc] init];
        [label setNumberOfLines:0];
        label.text=[detailDict valueForKey:@"ABC"];
        [label setFont:[UIFont fontWithName:@"Georgia" size:16.0]];
        CGSize labelsize=[label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(250, 1000.0) lineBreakMode:UILineBreakModeWordWrap];
        int y=0;
        label.frame=CGRectMake(38, y, 245, labelsize.height);
        [label setBackgroundColor:[UIColor clearColor]];
        [label setTextColor:[UIColor whiteColor]];
        scrollView.showsVerticalScrollIndicator = NO;
        y+=labelsize.height;
        [scrollView setContentSize:CGSizeMake(200,y+50)];
        [scrollView addSubview:label];
        [label release];

Here Y is used to increase or decrease the label size as the text.

Upvotes: 1

Related Questions