我正在从 Localizable.strings 中读取字符串,其中包含类似于 Android 应用程序的 strings.xml 中的内容
"testShort" = "A <b>short</b>\ntest with another<b>bold text</b>";
粗体和换行是我在文本中仅有的两个格式属性。我正在尝试开发这样的方法几天但没有成功:
func ConvertText(inputText: String) -> NSAttributedString {
// here comes the conversion to a representation with Helvetica 14pt and Helvetica-Bold 14pt including line feeds.
}
我的最终目标是在 UITextView 的属性文本中显示文本。
在不了解 Objective-C 的情况下对 Swift 和 iOS 有点陌生,我发现很难进行字符串操作,因为它们非常不同且复杂,并且所有示例都在 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
这里的主要问题\n
是没有转换,字体非常小而且不同。
接下来,我尝试手动将文本的一部分加粗。它似乎是这样工作的:
var newText = NSMutableAttributedString(string: inputText)
newText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 14.0)!, range: NSRange(location:2,length:4))
现在我尝试在文本中搜索属性,删除它们并使用 addAttribute 有点像
// Start of bold text
var range = newText.rangeOfString("<b>")!
// End of bold text
var range2 = newText.rangeOfString("</b>")!
// replacing attributes
newText = newText.stringByReplacingCharactersInRange(range, withString: "")
newText = newText.stringByReplacingCharactersInRange(range2, withString: "")
// creating a range for bold => error "'String.Index' is not convertible to 'int'"
// how to do such a thing
var boldRange = NSMakeRange(range.startIndex, range2.endIndex -3)
// setting bold
newText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 14.0)!, range: boldRange)
这整个范围是我目前的主要问题,因为它与字符串中的简单位置完全不同。
这个问题是缺乏(或隐藏得很好)文档的一个很好的例子:
addAttribute
想要一个 NSRange,似乎根据rangeOfString
我收到的错误消息提供了一个通用范围 - 但没有关于它的信息。Xcode 中的 Search Documentation 按钮rangeOfString()
指向 NSString。在那里搜索rangeOfString()
说它返回NSRange
。单击它会导致类型别名的信息,该别名_NSRange
又具有两个名为location
和的 NSUInteger 属性length
。我在 XCode 中看到的 startIndex 和 endIndex 属性在哪里?很混乱...
如果你能给我一些片段或提示我在这里错了,甚至是方法体,那就太好了,因为我仍然希望如果你对 iOS 和 Swift 了如指掌,这不会太难。我的目标是支持 iOS 7.1,但如果它在 iOS 8 上更容易,它也很好。