Search code examples
iosobjective-cnsmutableattributedstring

NSMutableAttributedString Crashing App


I'm doing something wrong with the range (I think) in setting this NSMutableAttributedString. Can anyone tell me why this is crashing my program? It looks right to me, but I'm obviously wrong! Thanks.

NSString *placeHolderString = @"USERNAME";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
float spacing = 5.0f;

// crashes on this line
[attributedString addAttribute:NSKernAttributeName
                         value:@(spacing)
                         range:NSMakeRange(0, [placeHolderString length])];

self.userNameTextField.attributedPlaceholder = attributedString;

Solution

  • What I think was causing your issue is that you were never really accounting for your placeholderString in the first place. In addition, your value parameter could simply use numberWithFloat as the application would then known what type you are using all the time.

    Once you account for the placeHolderString, you are then going to use the length for the attributeString, as it now just contains the contents of your placeholderString. Then we just simply copy that string which contains your attribute using the UITextField property attributedText.

    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:placeHolderString];
    float spacing = 5.0f;
    [attributeString addAttribute:NSKernAttributeName
                            value:[NSNumber numberWithFloat:spacing]
                            range:(NSRange){0,[attributeString length]}];
    userNameTextField.attributedText = [attributeString copy];
    

    For more context, attributes like NSUnderlineStyleAttributeName exist and you can do some really powerful things with NSMutableAttributedString. Refer to the documentation for options.