rdo*_*gan 9 objective-c nsattributedstring uilabel nstextattachment ios
我有一个UILabel显示NSAttributedString.该字符串包含文本和UIImagea NSTextAttachment.
在呈现时,有没有一种方式来获得的位置NSTextAttachment的UILabel?
编辑
这是我想要达到的最终结果.
当文本只有1行长时,图像应该在正确的边缘UILabel.简单:

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

我可以想到一个解决方案(这更像是一种解决方法),它仅适用于有限的情况。假设您的NSAttributedString左侧包含文本,右侧包含图像,您可以计算文本的大小并获取NSTextAttachmentsizeWithAttributes :的位置。这不是一个完整的解决方案,因为只能使用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
Run Code Online (Sandbox Code Playgroud)
希望这能为您提供一些提示。
编辑:
如果您有换行,您可以尝试以下代码(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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3659 次 |
| 最近记录: |