環境: Swift3
StroyBoard 上で UILabel の文字列を Plain ではなく Attributed で設定し、その文字列内の PlaceHolder を後から別の文字列に置き換えたいケースがあり必要になった。
NSMutableAttributedString#replaceCharacters(in:with:)
メソッドを使用する。
まず、NSAttributedString の Extension としてメソッドを追加する。
extension NSAttributedString { func replace(pattern: String, replacement: String) -> NSMutableAttributedString { let mutableAttributedString = self.mutableCopy() as! NSMutableAttributedString let mutableString = mutableAttributedString.mutableString while mutableString.contains(pattern) { let range = mutableString.range(of: pattern) mutableAttributedString.replaceCharacters(in: range, with: replacement) } return mutableAttributedString } }
そして、以下のように呼び出して使う。
@IBOutlet weak var detailLabel: UILabel? override func viewDidLoad() { super.viewDidLoad() if let attributedText = self.detailLabel?.attributedText { self.detailLabel?.attributedText = attributedText.replace(pattern: "置き換えたい文字列", replacement: "新しい文字列") } }