0

我想要一个最大宽度为 100 的 UILabel,然后是一个 UIImage,我该如何在界面生成器中做到这一点?我希望如果文本较短,则标签小于 100,但 UIImage 就在标签后面。

4

3 回答 3

5

您可以使用iOS 7 提供的NSTextAttachment类。无需使用框架。

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"image.png"];
NSAttributedString *attachmentAttrString = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *str= [[NSMutableAttributedString alloc] initWithString:@"hello"];
[str appendAttributedString:attachmentAttrString];
myLabel.attributedText = str;
于 2015-05-06T09:42:57.527 回答
2

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

首先初始化标签和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)];

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

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);
于 2012-10-19T07:00:24.600 回答
1

我想添加我的快速解决方案:

    let label = UILabel()

    let attributedString = NSMutableAttributedString(string: "Hello".uppercaseString)
    let attachment = NSTextAttachment()
    attachment.image = UIImage(named:"hello")

    attributedString.appendAttributedString(NSAttributedString(attachment:attachment))

//  use the following method to insert the image at any index
//  attributedString.insertAttributedString(NSAttributedString(attachment:attachment), atIndex: 0)

    label.attributedText = attributedString
于 2015-12-07T11:47:41.573 回答