防止部分NSAttributedString中的换行符 [英] Preventing line breaks in part of an NSAttributedString

查看:500
本文介绍了防止部分NSAttributedString中的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UILabel ,其中包含较大的主要文字,后跟较小的文字,告诉您是谁说的:

I am working on a UILabel which features large main text followed by smaller text that tells you who said it:

现在它基本上是一个 NSAttributedString ,在小文本上有一个font属性。

Right now it is basically an NSAttributedString with a font attribute on the small text.

我想设置一下所以大文字包装但小文字没有。也就是说,如果文本将与正确项目中的文本完全相同,则它应该按原样呈现,但它会像在左项中一样包裹,整个小文本应该出现在下一行:

I would like to set things up so the big text wraps but the small text doesn't. I.e., If the text will all fit on the same line as it does in the right item, it should render as is, but it it would wrap like in the left item, the whole of the small text should appear on the next line:

与我想要达到的相当的HTML是:

The HTML equivalent of what I'm trying to achieve is:

Title <nobr>Subtitle</nobr>
- or -
Title <span style="white-space:nowrap">Subtitle</span>

我尝试用 NSHTMLTextDocumentType 并且它似乎没有直接翻译。

I've tried converting both of these to NSAttributedStrings with NSHTMLTextDocumentType and it doesn't appear to do a direct translation.

推荐答案

按照rmaddy的建议,我得到了我想要的效果是将空格和短划线替换成不间断的替代方案:

Following rmaddy's suggestion, I was able to get the effect I wanted by replacing spaces and dashes with their non-breaking alternatives:

Objective-C:

Objective-C:

NS_INLINE NSString *NOBR(NSString *string) {
return [[string stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"] 
                stringByReplacingOccurrencesOfString:@"-" withString:@"\u2011"];

}

NSAttributedString *username = [[NSAttributedString alloc] 
    initWithString:NOBR(hotQuestion.username) attributes:nil];
...

Swift(注意稍有不同的转义码格式):

Swift (note the slightly different escape code format):

func nobr(_ string:String) -> String {
    return string
        .stringByReplacingOccurrencesOfString(" ", withString: "\u{a0}")
        .stringByReplacingOccurrencesOfString("-", withString: "\u{2011}")
}

let username = NSAttributedString(string:nobr(hotQuestion.username, attributes:nil))

这篇关于防止部分NSAttributedString中的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆