【发布时间】:2018-04-20 02:45:43
【问题描述】:
我试图向用户展示一个 TableView,在表格视图的每个单元格中都有一个图像和一个 textView,我为 textView.text 提供每个单元格的单个字符串,但是在每个字符串中,我'希望有多种字体。例如,字符串的一部分大小为 20 和粗体,其余部分大小为 14 和常规。您可以在下图中看到我在我的应用中拥有的内容
如您所见,我尝试编辑“您如何交易股票?” NSMutableAtributtedString 字符串的一部分,但是输出是它的设置,而不是具有选定属性的字符串。我使用的代码如下:
let title1 = "How do you trade stocks?"
let atributtedTitle1 = NSMutableAttributedString(string: title1)
atributtedTitle1.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont(name: "AvenirNext-Bold", size: 20)!], range: getRangeOfSubString(subString: title1, fromString: title1))
var textViews:[String] = ["\(atributtedTitle1)The stock market is one of the best ways you can build up wealth. The stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealth. The stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealth. The stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealth. The stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealth. The stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealthThe stock market is one of the best ways you can build up wealth"]
加载 textView 文本通常是在 tableView 中完成的
cell.descriptionTextView.text = textViews[indexPath.row]
而我用来计算NSMutableAtributtedString中范围的函数如下:
func getRangeOfSubString(subString: String, fromString: String) -> NSRange {
let sampleLinkRange = fromString.range(of: subString)!
let startPos = fromString.distance(from: fromString.startIndex, to: sampleLinkRange.lowerBound)
let endPos = fromString.distance(from: fromString.startIndex, to: sampleLinkRange.upperBound)
let linkRange = NSMakeRange(startPos, endPos - startPos)
return linkRange
}
如何在单个字符串中包含多种字体和大小,以便将其提供给单个 textView?
【问题讨论】:
-
我贴的在第二行和第三行,那是我唯一一次使用NSMutableAttributedString
标签: ios swift uitableview uitextview