将UIView设置为根据UILabel调整大小

3
我希望我的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个回答

2
使用 https://gist.github.com/2596057(这是Marco Arment的子类化UILabel)。
或者,您可以使用resizeHeightToFitText方法的代码来完成相同的操作,而无需使用IPInsetLabel。
一旦标签被调整大小以适应文本,根据高度和宽度设置标签的起点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接