Problem with dynamic width UILabel

Discussion in 'iOS Programming' started by computerartist, Oct 13, 2010.

  1. computerartist macrumors newbie

    Joined:
    Sep 4, 2010
    #1
    I am having the worst time trying to figure out why I cannot get the following code to output the correct width. When I use the following code to get the width it works fine and outputs 232. In this code I hard code in the string.

    Code:
    UILabel *labelDescription = [[UILabel alloc]  init];
    labelDescription.font = [UIFont boldSystemFontOfSize:12];
    labelDescription.text = @"The Rise of Middle-of-the-Road Radicals";
    CGSize size = [labelDescription.text sizeWithFont:labelDescription.text constrainedToSize:CGSizeMake(290, 32) lineBreakMode:UILineBreakModeWordWrap];
    
    Code:
    NSLog(@"%@", [NSNumber numberWithInt:size.width]);
    

    But if I use the following from an NSMutable Array and NSMutable string from the array I get a width of 352. What is going on here?

    Code:
    UILabel *labelDescription = [[UILabel alloc]  init];
    labelDescription.font = [UIFont boldSystemFontOfSize:12];
    
    NSMutableArray *cellTitleArray1 = [finalArraySortArrayElements2 objectAtIndex:indexPath.section];
    NSMutableArray *cellTitleArray2 = [cellTitleArray1 objectAtIndex:indexPath.row];
    labelDescription.text = [cellTitleArray2 objectAtIndex:0];
    
    CGSize size = [labelDescription.text sizeWithFont:labelDescription.text constrainedToSize:CGSizeMake(290, 32) lineBreakMode:UILineBreakModeWordWrap];
    
    Code:
    NSLog(@"%@", [NSNumber numberWithInt:size.width]);
    
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    At a minimum, the red-hilited code is wrong.

    Are you getting warnings when this is compiled? If so, don't ignore them. You should probably set the project or target setting that all warnings are treated as errors.

    If you're not getting warnings, are you sure that what you've posted is exactly what you're compiling?

    You also need to provide evidence that the blue-hilited code is resulting in exactly the same string as when you use a literal. In short, exactly how do you know that the strings are the same? Guessing, expecting, believing, or hoping don't count as evidence. Debugging is the process of systematically obtaining evidence that your expectations or beliefs are true.
     

Share This Page