代码之家  ›  专栏  ›  技术社区  ›  pankaj

动态增加uilabel的宽度

  •  0
  • pankaj  · 技术社区  · 14 年前

    我想根据要显示的文本长度动态地为标签指定宽度。标签是它自己添加到uiview上的。我正在使用下面的代码,但我仍然得到较短宽度的标签。

    - (id)initWithFrame:(CGRect)frame OrangeText:(NSString*)orange WhiteText:(NSString*)white {
    if ((self = [super initWithFrame:frame])) {
        CGSize textSize = [orange sizeWithFont:[UIFont systemFontOfSize:14]];
        OrangeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, textSize.width, textSize.height+2)];
        OrangeLabel.text = orange;
        OrangeLabel.backgroundColor = [UIColor clearColor];
        OrangeLabel.textColor = [UIColor orangeColor];
        [self addSubview:OrangeLabel];
    
        WhiteLabel = [[UILabel alloc] init];
        CGSize whiteTextSize = [white sizeWithFont:[UIFont systemFontOfSize:14]];
        WhiteLabel.frame = CGRectMake(OrangeLabel.frame.size.width+35, 5, whiteTextSize.width, whiteTextSize.height);
        WhiteLabel.text = white;
        WhiteLabel.backgroundColor = [UIColor clearColor];
        WhiteLabel.textColor = [UIColor whiteColor];
        [self addSubview:WhiteLabel];        // Initialization code
    }
    return self;
    

    }

    1 回复  |  直到 14 年前
        1
  •  6
  •   Bongeh    14 年前

    我想你在找这个方法

    [myLabel sizeToFit];

    这应该调整标签框的大小以适应其内容。