Pandey_Laxman
Pandey_Laxman

Reputation: 3908

how to get the correct size of NSString or check Whether it would fit in UILabel or Not?

I have an UILabel that can display only three lines of Text and its height and width are (312,44) inside an UITableViewCell what do I want to do that if UILabel text is more or getting ... (dot, dot) Then display the text on Alert view when user long press on that particular cell inside UITableView.

enter image description here

But the problem I am facing if text is doted inside the label it calculates NSString size less than UILabel size in the below code. I am frustrating whats going wrong with it.

Here is UILabel inside UITableView

enter image description here

When I set "Breakpoint" in the code I am getting the size for the below string is (309.46,42.97) that is less than lblSize

@"Headline Description : Parker is located in 47 countries around the world Parker supports 142 divisions with 311 manufacturing locations in 47 countries globally. Our unrivalled industrial distribution network extends to approximately 13,000 locations globally. Through this extensive network of local, independent businesses, Parker can bring its products and services to customers in 104 countries globally. This includes continued penetration of the Parker Store network of industrial retail outlets, which is approaching 2,000 locations. "

-(IBAction)longGuestureTriggered:(UILongPressGestureRecognizer*)longPressGesture
{
    if (longPressGesture.state == UIGestureRecognizerStateEnded)
    {

        UILabel* lbl=(UILabel*)longPressGesture.view;
        CGSize size = [lbl.text sizeWithFont:lbl.font constrainedToSize:lbl.bounds.size lineBreakMode:lbl.lineBreakMode];
        CGSize lblSize=lbl.bounds.size;
        if (size.height> lblSize.height && size.width>lblSize.width)
        {
            UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"Detail View" message:lbl.text delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];

            [alertView show];
        }
    }

}

Upvotes: 0

Views: 106

Answers (1)

gWiz
gWiz

Reputation: 1284

The problem is that you are asking for a size that fits the CURRENT label. You should ask for a size that fits a much taller label. So instead of

CGSize size = [lbl.text sizeWithFont:lbl.font constrainedToSize:lbl.bounds.size lineBreakMode:lbl.lineBreakMode];

you should use:

CGSize size = [lbl.text sizeWithFont:lbl.font constrainedToSize:CGSizeMake(lbl.bounds.size.width, 1000) lineBreakMode:lbl.lineBreakMode];

Upvotes: 2

Related Questions