洪嘉駿
洪嘉駿

Reputation: 11

Auto fit UILabel text size to fit UILabel width

I am doing a calendar app. In year page, I want to show 12 months a year and each month shows 30 days.

Here are questions:

1.Now I am trying to add 30 days into one uilabel with [nsstring stringbyappendingstring], but how to auto fit each gap between each day?

I can only get like

1||2||3||4||5||6||7

8||9||10||11||12||13||14

I want it looks like

1 || 2 || 3 || 4 || 5 || 6 || 7

8 || 9 ||10||11||12||13||14

|| <- this means each gap

2.or should I add uilabel for each day?but I will get 30 uilabel per month, an 365 uilabel a year in one view, this sounds stupid.

can anyone help me, please!

Upvotes: 0

Views: 446

Answers (1)

Sanjay Mohnani
Sanjay Mohnani

Reputation: 5967

You need to use only one label to show all the dates which the required spacing

1) Create a multiline label, set it's width.

2) Create a string by appending all the dates by using stringByAppendingsString with the required spacings.

3) Calculate the height of the label by keeping it's width fixed using below API-

#define LABELS_MAX_HEIGHT             10000.0f


CGSize constraintSize = CGSizeMake(label.frame.size.width, LABELS_MAX_HEIGHT);

NSAttributedString *attributedText = [[[NSAttributedString alloc] initWithString:datesString attributes:@{NSFontAttributeName: label.font}] autorelease];
        CGRect rect = [attributedText boundingRectWithSize:constraintSize
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        [label setSize:rect.size];

Upvotes: 1

Related Questions