Sunday, 18 November 2012

How to make subString of a NSString bold in iOS

Hi all,

     How to make subString of a NSString bold,is it possible to change subString font?

     Example: "Hi i am working in Eminosoft"
         from above statement i want to make "Eminosoft" is bold
like   "Hi i am working in Eminosoft".

please suggest me...

-iOS Developer

2 comments:

  1. //
    // ViewController.m
    // stringOperation
    //
    // Created by Mac-5 on 11/20/12.
    // Copyright (c) 2012 Mac-5. All rights reserved.
    //

    #import "ViewController.h"

    @interface ViewController ()

    @end

    @implementation ViewController
    @synthesize label,Original;

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    }

    - (void)didReceiveMemoryWarning
    {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

    - (IBAction)Convert:(id)sender
    {
    NSString *text = @"Updated: 2012/10/14 21:59";


    if ([label respondsToSelector:@selector(setAttributedText:)])
    {
    // iOS6 and above : Use NSAttributedStrings
    const CGFloat fontSize = 20;
    UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
    UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
    UIColor *foregroundColor = [UIColor redColor];

    // Create the attributes
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
    boldFont, NSFontAttributeName,
    foregroundColor, NSForegroundColorAttributeName, nil];
    NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
    regularFont, NSFontAttributeName, nil];
    const NSRange range = NSMakeRange(8,12); // range of " 2012/10/14 ". Ideally this should not be hardcoded

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
    [[NSMutableAttributedString alloc] initWithString:text
    attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [label setAttributedText:attributedText];
    } else {

    [label setText:text];

    }



    }
    @end

    ReplyDelete
    Replies
    1. Hi SrinnivasReddy,

      Thanks for the reply & Good work. But the above functionality will supports only on iOS6 this is not for below iOS6.
      For an example:
      [label setAttributedText: ];
      //In the above statement setAttributedText method is only available on iOS6 not below than that.

      Delete