我认为这是一个常见问题,当你有一组单词时,你不想要断线。防止在NSAttributedString中换行
有时,这些词之间的字符是一个空格或连字符,等等。对我来说,这是一个点:)
这是我的文字50.0/80.0
最后我做到了使用尺寸标签和测量我需要多少空间对于字符串特别是:
UIFont *fontAwardNumber = [UIFont fontWithName:@"DIN-Bold" size:20];
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize labelSize = (CGSize){customCell.awardValueLabel.bounds.size.width, FLT_MAX};
CGRect rectNeededForAwardNumber = [awardNumber boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: fontAwardNumber} context:context];
if (rectNeededForAwardNumber.size.height > customCell.awardValueLabel.bounds.size.height) {
//We need to add a breakline
NSRange range = [awardNumber rangeOfString:@"/"];
if (range.location != NSNotFound) {
awardNumber = [awardNumber stringByReplacingCharactersInRange:range withString:@"/\n"];
}
}
我发现了其他解决方案,如更换你的空间或连字符的字符牢不可破:
Preventing line breaks in part of an NSAttributedString
但我的问题是更普遍的,并NSAttributedString提供的东西来定义一组词作为非易碎的?或者是否有更简单的方法来处理一般词汇?
使用'NSParagraphStyle',设置换行符模式为'ByWordWrapping',看到这个答案... http://stackoverflow.com/a/19197903/499581 –
换行符使用\,而不是'/'虽然。你知道的,对吧? – LinusGeffarth