场景
我有一个JSON Feed,可在其中获取有关城市地点的所有信息。设计看起来像这样(见附图)。
设计需要合并文本, URL文本,不同字体大小的文本。有时,URL可能不存在于JSON feed中。
问题
哪个选项是在TableViewCell中进行布局的最佳方法?
我认为选项3是最简单的,因为我读到在Swift 4中可以使用新的字符串文字。用换行符连接所有字符串,然后将它们放在UITextView中。但我认为它不支持格式化文本。
请寻求反馈
答案 0 :(得分:0)
更新:根据以下研究,我发现您可以使用以下方法解决此问题:
- NSAttributedStringKey
- NSAttributedString
- NSMutableAttributedString
第一步
我创建了一个名为generateEntry
的私有函数,该函数返回一个NSMutableAttributedString
private func generateEntry(bType: String, bTitle:String, bDescription:String, bUrl: String) -> NSMutableAttributedString {
// -- passed in parameters
let bookmarkType:String = bType
let bookmarkTitle:String = bTitle
let bookmarkDesc: String = bDescription
let bookmarkUrl: String = bUrl
// -- type
// Step 1 - you need to create the attribute for the string you want to change. Size, color, kern effect
// Step 2 - then you create a NSAttributedString and apply the attributes from the previous line
let bTypeAttribute = [NSAttributedStringKey.font: UIFont(name: "Arial", size: 14), NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.kern: NSNumber(value: 0.5)]
let test: NSAttributedString = NSAttributedString(string: bookmarkType.uppercased() + ": ", attributes: bTypeAttribute as Any as? [NSAttributedStringKey : Any])
// -- title
let bTitleAttribute = [NSAttributedStringKey.font: UIFont(name: "Arial-Bold", size: 18), NSAttributedStringKey.foregroundColor: UIColor.black]
let testb: NSAttributedString = NSAttributedString(string: bookmarkTitle, attributes: bTitleAttribute as Any as? [NSAttributedStringKey : Any])
// -- description
let bDescriptionAttribute = [NSAttributedStringKey.font: UIFont(name: "Arial", size: 18), NSAttributedStringKey.foregroundColor: UIColor.black]
let testc: NSAttributedString = NSAttributedString(string: ": " + bookmarkDesc, attributes: bDescriptionAttribute as Any as? [NSAttributedStringKey : Any])
// -- url
let bURLAttribute = [NSAttributedStringKey.font: UIFont(name: "Arial-Italic", size: 18), NSAttributedStringKey.foregroundColor: UIColor.black]
let testd: NSAttributedString = NSAttributedString(string: bookmarkUrl, attributes: bURLAttribute as Any as? [NSAttributedStringKey : Any])
// combine the strings
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(test)
mutableAttributedString.append(testb)
mutableAttributedString.append(testc)
mutableAttributedString.append(NSAttributedString(string: "\n"))
mutableAttributedString.append(testd)
return mutableAttributedString
}
第2步
然后,在我的tableViewCell中,我可以使用此私有方法来生成NSMutableAttributedString
并将其应用于我的自定义tableViewCell。但是,您需要确保使用cell.descriptionLabel.text
attributedText
let testText = generateEntry(bType: "Type", bTitle: "PLACE", bDescription: "A description...", bUrl: "URL")
cell.descriptionLabel?.attributedText = testText