我有一个UILabel显示一个NSAttributedString。该字符串包含文本和UIImage作为NSTextAttachment。
呈现时,是否有方法获取NSTextAttachment在UILabel中的位置?
编辑
这是我想要达到的最终结果。
当文本只有1行长时,图像应该就在UILabel的边缘。简单:

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

发布于 2014-06-10 08:24:26
我可以想到一个解决方案(更多的是一个解决办法),它只适用于有限的情况。假设您的NSAttributedString包含左侧的文本和右侧的图像,您可以计算文本的大小,并使用sizeWithAttributes:获取NSTextAttachment的位置。这不是一个完整的解决方案,因为只能使用x坐标(即文本部分的width )。
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):
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);https://stackoverflow.com/questions/23999544
复制相似问题