tzer
tzer

Reputation: 280

setDefaultTextAttributes on UITextField does not work

I have a problem assigning text attributes (font,color, kerning) to an empty UITextField. Here is some sample code:

// testinput is an UITextField created in storyboard
//
 [testinput setDefaultTextAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0], NSForegroundColorAttributeName: [UIColor redColor]}  ];

That should - in theory - change font & color, but nothing happens. I've also tried different ways of creating the dictionary, no change. Please do not advise to use an attributed string, the UITextField must be initially empty.

Any help would be appreciated.

Upvotes: 0

Views: 4051

Answers (3)

Greg
Greg

Reputation: 25459

If you use setDefaultTextAttributes the changes will apply to textAttribute not text property of UITextField. So if you want to use text property, and I assume you want you should use, try:

testinput.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0];
testinput.textColor = [UIColor redColor]

//Extended

I'm afraid you cannot use it in the way you want. This is from apple documentation:

By default, this property returns a dictionary of text attributes with default values.
Setting this property applies the specified attributes to the entire text of the text field. Unset attributes maintain their default values.

It looks like when you use defaultTextAttributes property you will get only a dictionary and f you want to set it you have to create attribute string with attributes(dictionaries):

Upvotes: 0

Manuel Escrig
Manuel Escrig

Reputation: 2835

Swift 4 version

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let currentAttributes = textField.typingAttributes
    if var attributes = currentAttributes {
        attributes[NSAttributedStringKey.foregroundColor.rawValue] = UIColor.white
        attributes[NSAttributedStringKey.font.rawValue] = UIFont.systemFont(ofSize: 26)
        textField.typingAttributes = attributes
    }

    return true
}

Upvotes: 0

tzer
tzer

Reputation: 280

Found a solution after reading Gregs comment. To set the initial attributes in an empty UITextField, use the

@property(nonatomic, copy) NSDictionary *typingAttributes

property. It must be set in one of the delegate methods of the UITextField:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
   NSDictionary* d = textField.typingAttributes;
   NSMutableDictionary* md = [NSMutableDictionary dictionaryWithDictionary:d];

   md[NSFontAttributeName] = [UIFont systemFontOfSize:30];
   md[NSKernAttributeName] = @(9.5f);

   textField.typingAttributes = md;
   return YES;
}

Upvotes: 4

Related Questions