Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Created June 25, 2018 11:55
Show Gist options
  • Save KentarouKanno/01dbe7d2120ad1ce68a1bb843f83940a to your computer and use it in GitHub Desktop.
Save KentarouKanno/01dbe7d2120ad1ce68a1bb843f83940a to your computer and use it in GitHub Desktop.

NSAttributedString+

extension NSAttributedString {

    /// 指定した文字列の色を変える
    ///
    /// - Parameters:
    ///   - trueText: 文字列全部
    ///   - answearWord: 色を変える文字列
    /// - Returns: 変換したNSAttributedString
    static func answearHighlight(trueText: String, answearWord: String) -> NSAttributedString {
        
        let trueTextColor = #colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1294117647, alpha: 1)
        let answearWordColor = #colorLiteral(red: 0.2549019608, green: 0.7450980392, blue: 0, alpha: 1)
        let stringAttributes: [NSAttributedStringKey : Any] = [
            .foregroundColor: trueTextColor,
            .font: UIFont.systemFont(ofSize: 16.0)
        ]
        let answearAttributes: [NSAttributedStringKey : Any] = [
            .foregroundColor: answearWordColor,
            .font: UIFont.systemFont(ofSize: 16.0)
        ]
        let attributedString = NSMutableAttributedString(string: trueText, attributes: stringAttributes)
        // 任意の文字列ある位置を取得する
        let range = (trueText as NSString).range(of: answearWord)
        attributedString.addAttributes(answearAttributes, range: range)
        
        return attributedString
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment