如何在自动收缩标签后添加UILabel而不重叠第二个标签

时间:2012-07-15 16:48:29

标签: iphone ios uilabel

我正在对iPhone视图中的标签进行操作,第一个是基于从远程Web服务获取的字符串内容自动调整大小但是我旁边有另一个UILabel但是当第一个标签文本变得非常时长期它与最后一个标签重叠,我该如何避免它......

1 个答案:

答案 0 :(得分:1)

如果您通过界面构建​​器

创建了标签

创建两个 UILabel IBOutlet属性作为lbl1和lbl2。 然后将IBOutlet连接到接口构建器。 然后在 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";

然后不要忘记再次编写/执行/调用代码 lbl2.frame = CGRectMake(lbl1.frame.origin.x + lbl1.frame.size.width,lbl1 .frame.origin.y + lbl1.frame.size.height,100,50)]; ,同时将文本分配给lbl1。

如果您通过代码创建了标签

以下代码对我有用

- (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];
}