0

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;
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
  • It would help if you provided details about the crash including the actual line causing the crash and the complete error message. – rmaddy Aug 16 '14 at 02:49

1 Answers1

2

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.

  • While the code in your answer seems correct, a good answer provides at least some explanation. – rmaddy Aug 16 '14 at 02:50