You will need to use the attributed string NSAttributedString
. With text field it is best to have a delegate and implement the method on changing the characters in range. This will handle all the cases even when the user pasts the text from somewhere else.
So the NSMutableAttributedString
has a method to replace the string in range with a mutable attributed string which is perfect for this method. The new string received by the delegate must simply be converted to the attributed one with a currently set font.
Try something like this:
@interface AttributedTextField : NSObject<UITextFieldDelegate>
@property (nonatomic, strong) NSMutableAttributedString *attributedString;
@property (nonatomic, strong) UIFont *currentFont;
@end
@implementation AttributedTextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// ensure having a font
UIFont *font = self.currentFont;
if(font == nil) {
font = [UIFont systemFontOfSize:12.0f];
}
// ensure having a base string
if(self.attributedString == nil) {
self.attributedString = [[NSMutableAttributedString alloc] initWithString:@""];
}
// append the new string
[self.attributedString replaceCharactersInRange:range withAttributedString:[[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName: font}]];
textField.attributedText = self.attributedString; // assign the new text which is attributed
return NO; // return false as we are overriding the text
}
@end