-1

我正在创建一个字符串数组以与titleForFooterInSection表视图委托方法一起使用。每个字符串将跨越几行,并且需要强调一些单词。

我怎样才能让字符串中的选定单词只有粗体字?

我想实现这张图片中的内容: 带有粗体的表视图页脚

谢谢

4

1 回答 1

1

我在某个项目中所做的是我创建了一个像这样的对象:

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
于 2019-08-25T17:18:54.557 回答