How can I add a UILabel after auto shrink label without overlapping the second one

I'm doing to labels in iPhone view, the first one is auto sized based on the string contents fetched from a remote webservice although I have another UILabel right next to it but when the first label text became very long it overlaps the last label, how can I avoid it ...

Answers


If you created the Labels through interface-builder

Create two UILabel IBOutlet properties as lbl1 and lbl2. Then connect the IBOutlet's to interface builder. Then write the below code in viewDidLoad

[lbl1 setNumberOfLines:0];
lbl1.lineBreakMode = UILineBreakModeWordWrap;
[lbl1 sizeToFit];
lbl1.text = @"your text here";

lbl2.frame =  CGRectMake(lbl1.frame.origin.x + lbl1.frame.size.width,  lbl1.frame.origin.y + lbl1.frame.size.height, 100, 50)];    
[lbl2 setNumberOfLines:0];   
lbl2.lineBreakMode = UILineBreakModeWordWrap;   
[lbl2 sizeToFit];
lbl2.text = @"your text here";

Then don't forget to write/execute/call the code again lbl2.frame = CGRectMake(lbl1.frame.origin.x + lbl1.frame.size.width, lbl1.frame.origin.y + lbl1.frame.size.height, 100, 50)]; while assigning text to lbl1.

If you created the Labels through Code

The below code worked for me

- (void)viewDidLoad {

    //Adding first label
    UILabel* lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 100, 50)];
    lbl1.text = @"vbdsbfdshfisdhfidshufidhsufhdsf dhdsfhdksbf hfsdh fksdfidsf sdfhsd fhdsf sdhfh sdifsdkf ksdhfkds fhdsf dsfkdsfkjdhsfkjdhskfjhsdk fdhsf vbdsbfdshfisdhfidshufidhsufhdsf dhdsfhdksbf hfsdh fksdfidsf sdfhsd fhdsf sdhfh sdifsdkf ksdhfkds fhdsf dsfkdsfkjdhsfkjdhskfjhsdk fdhsf";
    [lbl1 setMinimumFontSize:8.0];
    [lbl1 setNumberOfLines:0];
    [lbl1 setFont:[UIFont systemFontOfSize:10.0]];
    lbl1.lineBreakMode = UILineBreakModeWordWrap;
    lbl1.backgroundColor = [UIColor redColor];
    [lbl1 sizeToFit];
    [self.view addSubview:lbl1];

    //Adding second label
    UILabel* lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(lbl1.frame.origin.x + lbl1.frame.size.width, lbl1.frame.origin.y + lbl1.frame.size.height, 100, 50)];  
    lbl2.text = @"vbdsbfdshfisdhfidshufidhsufhdsf dhdsfhdksbf hfsdh fksdfidsf sdfhsd fhdsf sdhfh sdifsdkf ksdhfkds fhdsf dsfkdsfkjdhsfkjdhskfjhsdk fdhsf vbdsbfdshfisdhfidshufidhsufhdsf dhdsfhdksbf hfsdh fksdfidsf sdfhsd fhdsf sdhfh sdifsdkf ksdhfkds fhdsf dsfkdsfkjdhsfkjdhskfjhsdk fdhsf";
    [lbl2 setMinimumFontSize:8.0];
    [lbl2 setNumberOfLines:0];
    [lbl2 setFont:[UIFont systemFontOfSize:10.0]];
    lbl2.lineBreakMode = UILineBreakModeWordWrap;
    lbl2.backgroundColor = [UIColor redColor];
    [lbl2 sizeToFit];
    [self.view addSubview:lbl2];

    [lbl1 release];
    [lbl2 release]; 

    [super viewDidLoad];
}

Need Your Help

Create a new aggregate collection from two existing collections?

mongodb pymongo database

I have a unique field in two collections which is "ip". One collection contains machine data and the other contains geographic data