1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import UIKit class Test3ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let targetString = "Updated 2012/10/14 21:59 PM" let range = NSMakeRange(7, 12) let range2 = NSMakeRange(19, 7) let label = UILabel(frame: CGRect(x:0, y:100, width:350, height:44)) label.backgroundColor = UIColor.white label.attributedText = attributedString(from: targetString, nonBoldRange: range, secondRange: range2) label.sizeToFit() view.addSubview(label) } func attributedString(from string: String, nonBoldRange: NSRange?, secondRange: NSRange?) -> NSAttributedString { let fontSize = UIFont.systemFontSize let attrs = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize), NSForegroundColorAttributeName: UIColor.red ] let nonBoldAttribute = [ NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: UIColor.blue ] let secondAttribute = [ NSFontAttributeName: UIFont(name: "Bodoni 72", size: fontSize * 2), // .HelveticaNeue(ofSize: fontSize), NSForegroundColorAttributeName: UIColor.green ] let attrStr = NSMutableAttributedString(string: string, attributes: attrs) if let range = nonBoldRange { attrStr.setAttributes(nonBoldAttribute, range: range) } if let range2 = secondRange{ attrStr.setAttributes(secondAttribute, range: range2) } return attrStr } } |
mostly taken from internet may by stackoverflow again.