我正在尝试获取一个格式为html的文本片段,以便在UITableViewCell中的iPhone上很好地显示.
到目前为止我有这个:
NSError* error;
NSString* source = @"<strong>Nice</strong> try, Phil";
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&error];
Run Code Online (Sandbox Code Playgroud)
这种作品.我得到一些粗体'好'的文字!但是......它还将字体设置为Times Roman!这不是我想要的字体.我想我需要在documentAttributes中设置一些内容,但是,我无法在任何地方找到任何示例.
我正在从Localizable.strings中读取字符串,其中包含类似于Android应用程序的strings.xml中的内容.
"testShort" = "A <b>short</b>\ntest with another<b>bold text</b>";
Run Code Online (Sandbox Code Playgroud)
粗体和换行是我文本中唯一的两个格式属性.我试图开发这样的方法几天没有成功:
func ConvertText(inputText: String) -> NSAttributedString {
// here comes the conversion to a representation with Helvetica 14pt and Helvetica-Bold 14pt including line feeds.
}
Run Code Online (Sandbox Code Playgroud)
我的最终目标是在UITextView的attributedText中显示文本.
在不知道Objective-C的情况下成为Swift和iOS的新手我发现很难做String操作,因为它们非常不同且复杂,所有示例都在Objective-C中.更令人困难的是,大多数API方法在Swift中不可用或与Objective-C不同......
这是我到目前为止尝试的方法体,这里有很多其他帖子:
var test = inputText.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!
attrStr = NSAttributedString(
data: test,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)!
return attrStr
Run Code Online (Sandbox Code Playgroud)
这里的主要问题\n是没有转换,字体非常小而且不同.
接下来,我尝试手动加粗文本的一部分.它看起来像那样:
var newText = NSMutableAttributedString(string: inputText)
newText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 14.0)!, range: NSRange(location:2,length:4))
Run Code Online (Sandbox Code Playgroud)
现在我尝试在文本中搜索属性,删除它们并使用类似的addAttribute
// Start of bold text
var …Run Code Online (Sandbox Code Playgroud) xcode nsattributedstring ios nsmutableattributedstring swift