Skip to content

Instantly share code, notes, and snippets.

@wvdk
Last active March 1, 2020 11:48
Show Gist options
  • Save wvdk/e8992e82b04e626a862dbb991e4cbe9c to your computer and use it in GitHub Desktop.
Save wvdk/e8992e82b04e626a862dbb991e4cbe9c to your computer and use it in GitHub Desktop.
Extension for changing text on a UILabel with an attributed string. With this method you can style in interface builder and easily change the text in code without losing attributes.
//
// Created by WVDK on 2/10/17.
// Copyright © 2017 Wesley Van der Klomp. All rights reserved.
//
// https://gist.github.com/wvdk/e8992e82b04e626a862dbb991e4cbe9c
//
import UIKit
extension UILabel {
func setTextWhileKeepingAttributes(string: String) {
if let newAttributedText = self.attributedText {
let mutableAttributedText = newAttributedText.mutableCopy()
mutableAttributedText.mutableString.setString(string)
self.attributedText = mutableAttributedText as? NSAttributedString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment