在UILabel之后放置一个UIImage

问题描述:

我希望UILabel的最大宽度为100,之后是UIImage,我该如何在界面构建器中执行此操作?我希望如果文本较短,标签小于100,但UIImage就在标签后面。

I want to have an UILabel with a max width of 100 and after that an UIImage, how can I do that in interface builder? I want that if the text is shorter the label is less than 100 but the UIImage is right behind the label.

你可以用这样的代码来做:

you can do it with code like this:

首先初始化标签和imageView

first init the label and the imageView

_label = [[UILabel alloc] initWithFrame:CGRectZero];
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(label.frame.origin.x + label.frame.size.width, label.frame.origin.y, 30, 30)];

然后当标签有文字时,你可以计算标签框架的宽度

then when the label has text , you can calc the width of the label`s frame

CGSize size = [_label.text sizeWithFont:[UIFont boldSystemFontOfSize:15]];
CGFloat width = size.width > 100 ? 100 : size.width;
CGFloat height = size.height;
_label.frame = CGRectMake(0, 0, width, height);