如何根据UILabel内容调整/设置UIView大小

时间:2014-01-30 12:37:13

标签: ios iphone uiview uilabel

我使用循环来创建动态UIView。但我无法根据UIView的大小创建UILabel,请帮助我,因为我可以继续进行..需要你的帮助..我会很感激

for(NSString *item in myArray)
{
    length = item.length;
    self.custom=[[CustomView alloc]init];
    self.custom.Label = [[UILabel alloc]initWithFrame:CGRectMake(40, yAxis, 100+item.length, 44)];
    [self.custom setFrame:self.custom.Label.frame];

    [self.custom sizeToFit];

    yAxis=yAxis+50;

    self.custom.tag=200+a;
    a++;

    [newViews addObject:self.custom];
    length = item.length;

    self.custom.Label = [[UILabel alloc]initWithFrame:CGRectMake(5,5,length+20,40)];

    self.custom.button=[[UIButton alloc]initWithFrame:CGRectMake(85,10,12,10)];

    [self.custom.Label setText:item];

    // Tell the label to use an unlimited number of lines
    [self.custom.Label setNumberOfLines:1];
    [self.custom.Label sizeToFit];
    self.custom.Label.textAlignment = UITextAlignmentCenter;

    ![this is image i have created uiview according the array values where uilabel more width than uiview so i need to set uiview according the uilabel][1]

    UIImage *btnImage = [UIImage imageNamed:@"button_droparrow.png"];
    [self.custom.button setImage:btnImage forState:UIControlStateNormal];
    [self.custom.button addTarget:self
                           action:@selector(buttonPressed:)forControlEvents:UIControlEventTouchDown];

    self.custom.button.tag=self.custom.button.tag+a;
    self.custom.backgroundColor=[UIColor greenColor];
    custom.Label.text=item;
    custom.Label.backgroundColor = [UIColor yellowColor];
    [self.custom addSubview:self.custom.button];
    [self.custom addSubview:custom.Label];
    // [self.custom addSubview:cv];

    [self.view addSubview:self.custom];
}

3 个答案:

答案 0 :(得分:0)

您可以使用以下代码获取基于UILabel内容的尺寸。

 NSString * countString = aLbl.text;
CGSize s = [countString sizeWithFont:[UIFont fontWithName:@"Helvetica-Light" size:12] constrainedToSize:CGSizeMake(100, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];  

使用以下代码更改任何视图的大小

CGRect  rect = aView.frame;
rect.size.width = s.width;
rect.size.height = s.height;
aView.frame = rect;

答案 1 :(得分:0)

尝试尺寸以适合标签或视图

[yourlabel sizeToFit];

[yourview sizeToFit];

答案 2 :(得分:-1)

更改setNumberOfLines:0并运行您的应用。我希望它对你有所帮助。我向你请求,如果有这个帮助你请投票给我。

[self.custom.Label setNumberOfLines:0];

self.custom.Label.text = @"xyz.................";
[self.custom.Label sizeToFit];