Search code examples
iosnsstringnsattributedstring

String and attributions problems


Ive been messing around with this without proper results. My code is as follows

NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc]initWithString:((User *)appDelegate.users[self.currentUserIndex]).name];
[nameString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0] range:NSMakeRange(0, nameString.length)];

NSString *adviceString = [[NSString alloc] initWithFormat:@"%@, remember be extra aware of the \n cat today. The dog index is 4, dogcatcher \n suggests you should at minimum wear \n a dog and apply cat...", [nameString string]];

So, it doesn't bold the username as desired. I tried using NSAttributedString for adviceString but then I can't use the initWithFormat: method and list the variables after the string, and I don't see any NSAttributedString equivalent. I wanted to you NSAttributedString instead of NSMutableAttributedString, but it doesn't seem to recognise the addAttribute:value:fontWithName:range method. Can anybody help me out? Any help much appreciated.


Solution

  • That's for sure, you need to use NSAttributedString also for adviceString to get attributed.

    The code goes like this, if you need to use stringWithFormat:

    NSString *fullName = @"Anoop Kumar Vaidya";
    NSMutableAttributedString *attributedName = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Hello %@", fullName]
                                           attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]}];
    

    In the attributes you can add few more desired/required attributes.

    EDIT 2:

    You may like to use some methods as :

    -(NSMutableAttributedString *)normalString:(NSString *)string{
        return [[NSMutableAttributedString alloc] initWithString:string
                                                      attributes:@{}];
    }
    
    -(NSMutableAttributedString *)boldString:(NSString *)string{
        return [[NSMutableAttributedString alloc] initWithString:string
                                                      attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]
                                                                   }];
    }
    

    And then use them as per your requirement:

    NSMutableAttributedString *attributedName = [self boldString:fullName];
    [attributedName appendAttributedString:[self normalString:@" is creating one"]];
    [attributedName appendAttributedString:[self boldString:@" bold"]];
    [attributedName appendAttributedString:[self normalString:@" string."]];