将UIView设置为基于UILabel调整大小

时间:2012-05-18 20:02:22

标签: ios xcode uiview alignment uilabel

Screenshot

我希望我的UILabel在这里显示为水平和中心。垂直在叠加层中我想要重叠UIView(在行家lorem ipsum文本后面的浅色alpha区域)调整大小以在顶部和底部给我10个像素的填充,但仍然自动拉伸其宽度。有谁能指出我正确的方向?我想让它尽可能地充满活力。

以下是我要看到的内容:

    descView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 160)];
    descView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    descView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];

    descLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 600, 120)];
    descLabel.center = CGPointMake(self.view.bounds.size.width/2, descView.bounds.size.height/2);

    descLabel.backgroundColor = [UIColor clearColor];
    descLabel.opaque = NO;
    descLabel.textAlignment = UITextAlignmentCenter;

    descLabel.text = currentPhoto.desc;
    descLabel.numberOfLines = 5;

    descLabel.textColor = [UIColor whiteColor];
    descLabel.autoresizingMask = UIViewAutoresizingFlexibleMargins;

    CGRect frame = descLabel.frame;
    frame.origin.x = (descView.frame.size.width - descLabel.frame.size.width)/2;

    descLabel.frame = frame;

    [self.view addSubview:descView];
    [descView addSubview:descLabel];

1 个答案:

答案 0 :(得分:2)

使用https://gist.github.com/2596057(Thats Marco Arment的子类UILabel)

(或)您可以使用resizeHeightToFitText方法的代码执行相同的操作而不使用hte IPInsetLabel

一旦标签的大小适合文字,请根据高度和宽度设置标签的原点