13

I want to make some part of a text string bold.

Eg: This is to be bold. This is normal string.

In Android, it can be easily achieved by using spannable strings. What is its equivalent in iOS?

Pang
  • 9,564
  • 146
  • 81
  • 122
WISHY
  • 11,067
  • 25
  • 105
  • 197

3 Answers3

32

Yes, it can be achieved with NSAttributedString:

NSString *yourString = @"This is to be bold. This is normal string.";
NSMutableAttributedString *yourAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
NSString *boldString = @"This is to be bold";
NSRange boldRange = [yourString rangeOfString:boldString];
[yourAttributedString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:boldRange];
[yourLabel setAttributedText: yourAttributedString];
Pang
  • 9,564
  • 146
  • 81
  • 122
Abhishek
  • 1,682
  • 2
  • 17
  • 29
3

Swift version:

@IBOutlet var theLabel: UILabel!
@IBOutlet var theTextview: UITextView!

        let theString = "Please satisfy three of the following password conditions" as NSString
        let theAttributedString = NSMutableAttributedString(string: theString as String)

        let boldString = "three"
        let boldRange = theString.range(of: boldString)
        let font = UIFont.boldSystemFont(ofSize: 20)

        theAttributedString.addAttribute(NSFontAttributeName, value: font, range: boldRange)
        theLabel.attributedText = theAttributedString
        theTextview.attributedText = theAttributedString
Naishta
  • 11,885
  • 4
  • 72
  • 54
0

You can achieve this using NSMutableAttributedString.

Refer Apple docs about NSMutableAttributedString.

I'd tried this answer's code to get bold and normal font in an UILabel.

Community
  • 1
  • 1
Nazik
  • 8,696
  • 27
  • 77
  • 123