Last active
January 24, 2019 06:23
-
-
Save Arime9/3b0bf98e352890319f3dc3418c26bdb5 to your computer and use it in GitHub Desktop.
【Swift+Extension】UILabelで、一部の文字だけ色を付ける ref: https://qiita.com/Arime/items/5ede5f9423a205cf2deb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let aLabel = UILabel() | |
aLabel.text = "あいうえお" | |
// "あいう"を赤色にする場合 | |
aLabel.addAccent(pattern: "あいう", color: .red) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
func nsRange(from range: Range<String.Index>) -> NSRange { | |
return NSRange(range, in: self) | |
} | |
func ranges(of searchString: String, options mask: NSString.CompareOptions = [], locale: Locale? = nil) -> [Range<String.Index>] { | |
var ranges: [Range<String.Index>] = [] | |
while let range = range(of: searchString, options: mask, range: (ranges.last?.upperBound ?? startIndex)..<endIndex, locale: locale) { | |
ranges.append(range) | |
} | |
return ranges | |
} | |
func nsRanges(of searchString: String, options mask: NSString.CompareOptions = [], locale: Locale? = nil) -> [NSRange] { | |
let ranges = self.ranges(of: searchString, options: mask, locale: locale) | |
return ranges.map { nsRange(from: $0) } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UILabel { | |
/// 対象の文字列に対して、アクセント色を付加する | |
/// | |
/// - Parameters: | |
/// - pattern: 対象の文字列 | |
/// - color: アクセント色 | |
func addAccent(pattern: String, color: UIColor) { | |
// String | |
let strings = [attributedText?.string, text].flatMap { $0 } | |
guard let string = strings.first else { return } | |
// Ranges | |
let nsRanges = string.nsRanges(of: pattern, options: [.literal]) | |
if nsRanges.count == 0 { return } | |
// Add Color | |
let attributedString = attributedText != nil | |
? NSMutableAttributedString(attributedString: attributedText!) | |
: NSMutableAttributedString(string: string) | |
for nsRange in nsRanges { | |
attributedString.addAttributes([.foregroundColor: color], range: nsRange) | |
} | |
// Set | |
attributedText = attributedString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment