首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSTextAttachment在UILabel中的位置?

NSTextAttachment在UILabel中的位置?
EN

Stack Overflow用户
提问于 2014-06-02 16:51:17
回答 1查看 4.3K关注 0票数 9

我有一个UILabel显示一个NSAttributedString。该字符串包含文本和UIImage作为NSTextAttachment

呈现时,是否有方法获取NSTextAttachmentUILabel中的位置?

编辑

这是我想要达到的最终结果。

当文本只有1行长时,图像应该就在UILabel的边缘。简单:

如果有多行,但仍然希望图像位于最后一行的末尾,则会出现问题:

EN

回答 1

Stack Overflow用户

发布于 2014-06-10 08:24:26

我可以想到一个解决方案(更多的是一个解决办法),它只适用于有限的情况。假设您的NSAttributedString包含左侧的文本和右侧的图像,您可以计算文本的大小,并使用sizeWithAttributes:获取NSTextAttachment的位置。这不是一个完整的解决方案,因为只能使用x坐标(即文本部分的width )。

代码语言:javascript
复制
NSString *string = @"My Text String";
UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Italic" size:24.0];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGSize size = [string sizeWithAttributes:attributes];
NSLog(@"%f", size.width); // this should be the x coordinate at which your NSTextAttachment starts

希望这能给你一些提示。

编辑:

如果有行包装,可以尝试以下代码(string是您要放入UILabel中的字符串,self.testLabel是UILabel):

代码语言:javascript
复制
CGFloat totalWidth = 0;
NSArray *wordArray = [string componentsSeparatedByString:@" "];

for (NSString *i in wordArray) {
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Italic" size:10.0];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    // get the size of the string, appending space to it
    CGSize stringSize = [[i stringByAppendingString:@" "] sizeWithAttributes:attributes];
    totalWidth += stringSize.width;

    // get the size of a space character
    CGSize spaceSize = [@" " sizeWithAttributes:attributes];

    // if this "if" is true, then we will have a line wrap
    if ((totalWidth - spaceSize.width) > self.testLabel.frame.size.width) {
        // and our width will be only the size of the strings which will be on the new line minus single space
        totalWidth = stringSize.width - spaceSize.width;
    }
}

// this prevents a bug where the end of the text reaches the end of the UILabel
if (textAttachment.image.size.width > self.testLabel.frame.size.width - totalWidth) {
    totalWidth = 0;
}

NSLog(@"%f", totalWidth);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23999544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档