Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created August 7, 2018 19:10
Show Gist options
  • Save alexpaul/8c1d982692216caee6f098cbd3203fb7 to your computer and use it in GitHub Desktop.
Save alexpaul/8c1d982692216caee6f098cbd3203fb7 to your computer and use it in GitHub Desktop.
NSAttributedString example that illustrates adding attributes to a String and setting the attributedText property on a UILabel
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let text = "stockholm, sweden"
let attributedText = NSMutableAttributedString.init(string: "stockholm, sweden", attributes: [:])
let range1 = (text as NSString).range(of: "stockholm")
let range2 = (text as NSString).range(of: "sweden")
attributedText.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 40, weight: .bold),
NSAttributedString.Key.foregroundColor : UIColor.blue
],
range: range1)
attributedText.addAttributes([NSAttributedString.Key.underlineStyle : NSUnderlineStyle.double.rawValue,
NSAttributedString.Key.foregroundColor : UIColor.orange,
NSAttributedString.Key.underlineColor : UIColor.black,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 24, weight: .medium)
],
range: range2)
nameLabel.attributedText = attributedText
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment