如何在Swift中以粗体字体在UITableView页脚中选择单词?
我正在创建一个字符串数组,用于如何在Swift中以粗体字体在UITableView页脚中选择单词?,swift,uitableview,footer,nsattributedstring,nsattributedstringkey,Swift,Uitableview,Footer,Nsattributedstring,Nsattributedstringkey,我正在创建一个字符串数组,用于titleForFooterInstition表视图委托方法。 每个字符串将跨越几行,其中一些单词需要强调 我怎么可能只选择了粗体字的字符串 我想实现这幅图中的目标: 谢谢我在某个项目中所做的是创建了一个如下对象: struct StringWithStyle { let font: UIFont let color: UIColor let text: String let backgroundcolor: UIColor
titleForFooterInstition
表视图委托方法。
每个字符串将跨越几行,其中一些单词需要强调
我怎么可能只选择了粗体字的字符串
我想实现这幅图中的目标:
谢谢我在某个项目中所做的是创建了一个如下对象:
struct StringWithStyle {
let font: UIFont
let color: UIColor
let text: String
let backgroundcolor: UIColor
init(font: UIFont,
color: UIColor,
text: String,
backgroundColor: UIColor = .clear) {
self.font = font
self.color = color
self.text = text
self.backgroundcolor = backgroundColor
}
var mutableAttrString: NSMutableAttributedString {
let attributes = [NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.backgroundColor: backgroundcolor]
return NSMutableAttributedString(string: text, attributes: attributes)
}
}
当然,您可以将字体设置为保持不变或创建应用程序中使用的常用样式
然后我有一个扩展名来传递带有样式的文本
static func textWithMultipleStyles(_ styles: [StringWithStyle]) -> NSMutableAttributedString {
var allTextStyles = styles
let text = allTextStyles.removeFirst().mutableAttrString
guard !allTextStyles.isEmpty else {
return text
}
for nextText in allTextStyles {
text.append(nextText.mutableAttrString)
}
return text
}
要使用您:
let example = String.textWithMultipleStyles([StringWithStyle(font: UIFont.boldSystemFont(ofSize: 16.0),
color: .black,
text: "First String"),
StringWithStyle(font: UIFont.systemFont(ofSize: 13, weight: .semibold),
color: .red,
text: "Second string")])
也许有更好的方法,但对于我这样的人来说,我在应用程序中使用了3-4种常用样式,可以轻松构建多个样式字符串
否则你可以使用范围
let boldText = "Some bold text"
let message = "This is a sentence with bold text \(boldText)"
let range = (message as NSString).rangeOfString(boldText)
let attributedString = NSMutableAttributedString(string: message)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range)
label.attributedText = attributedString
NSAttributedString
完全可以存储在数组中。然后如何将给定字符串中的某些选定单词更改为粗体字体?我发现了这个问题:但是NSMutableAttributedStrings不能使用rangeOfString
。为什么这被否决了?有什么问题吗?StringStyle
类型来自哪里?然后如何将此方法应用于字符串的选定部分?是的,抱歉。应该到处都是时尚。我更改并添加了一个示例谢谢!这很有趣,但我不确定我是否能够使用它,因为我想保持应用程序的可访问性,即使用。preferredFontStyle(for:)
。。。此文本将位于分组表视图的页脚中,每个页脚将有几行,其中一些单词必须为粗体。我不知道这是否能让它更清楚。然后你必须使用一些特定的词,我不太喜欢在代码中使用这些词。这样可能会使字符串的构造占用更多的行数,但至少对我来说,它更简单,更容易调试和以后更改。我认为我的答案适用于它,我不理解preferredFontStyle的问题。范围答案也应该有效。