【发布时间】:2018-08-09 11:12:32
【问题描述】:
【问题讨论】:
-
使用表格视图和 2 个包含左右内容的单元格。它不仅仅是标签,还有图像和时间标签。
-
@Bista 我想将时间标签与单个单元格中的图像对齐
-
@Arunkrishna 我想实现与您在问题中提到的完全相同的事情。你找到解决办法了吗?
【问题讨论】:
尝试使用类似这样的方法来定义最后一行的宽度(也许您需要根据自己的情况对文本容器进行更多调整):
public func lastLineMaxX(message: NSAttributedString, labelWidth: CGFloat) -> CGFloat {
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
let labelSize = CGSize(width: bubbleWidth, height: .infinity)
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: labelSize)
let textStorage = NSTextStorage(attributedString: message)
// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = .byWordWrapping
textContainer.maximumNumberOfLines = 0
let lastGlyphIndex = layoutManager.glyphIndexForCharacter(at: message.length - 1)
let lastLineFragmentRect = layoutManager.lineFragmentUsedRect(forGlyphAt: lastGlyphIndex,
effectiveRange: nil)
return lastLineFragmentRect.maxX
}
然后您可以决定最后一行是否有足够的位置放置您的日期标签
用法示例:
// you definitely have to set at least the font to calculate the result
// maybe for your case you will also have to set other attributes
let attributedText = NSAttributedString(string: self.label.text,
attributes: [.font: self.label.font])
let lastLineMaxX = lastLineMaxX(message: attributedText,
labelWidth: self.label.bounds.width)
【讨论】:
将 Swift 转换为 Objective-C
- (void)lastlineWidth {
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:self.label.font forKey:NSFontAttributeName];
NSAttributedString *message = [[NSAttributedString alloc] initWithString:self.label.text attributes:attrsDictionary];
CGSize labelSize = CGSizeMake(self.label.bounds.size.width, INFINITY);
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:labelSize];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:message];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
textContainer.lineFragmentPadding = 0.0;
textContainer.lineBreakMode = NSLineBreakByWordWrapping;
textContainer.maximumNumberOfLines = 0;
NSInteger lastGlyphIndex = [layoutManager glyphIndexForCharacterAtIndex:message.length-1];
CGRect lastLineRect = [layoutManager lineFragmentUsedRectForGlyphAtIndex:lastGlyphIndex effectiveRange:nil];
NSLog(@"lastLineWidth = %f", lastLineRect.size.width);
}
【讨论】: