Sunday, June 2, 2013

UITextField typingAttributes example in Objective C (iOS).

UITextField typingAttributes

The attributes to apply to new text being entered by the user.

@property(nonatomic,copy) NSDictionary *typingAttributes;

Discussion of [UITextField typingAttributes]
This dictionary contains the attribute keys (and corresponding values) to apply to newly typed text. When the text field’s selection changes, the contents of the dictionary are cleared automatically.

If the text field is not in editing mode, this property contains the value nil. Similarly, you cannot assign a value to this property unless the text field is currently in editing mode.

UITextField typingAttributes example.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.minimumLineHeight = 50.f;
mainTextView.typingAttributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];

Example of [UITextField typingAttributes].
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
        replacementString:(NSString *)string {
    NSDictionary* d = textField.typingAttributes;
    NSLog(@"%@", d);
    NSMutableDictionary* md = [NSMutableDictionary dictionaryWithDictionary:d];
    // md[NSUnderlineStyleAttributeName] = @(NSUnderlineStyleSingle);
    md[NSForegroundColorAttributeName] = [UIColor redColor];
    textField.typingAttributes = md;
    return YES;

UITextField typingAttributes example.
UITextView *textView = [self noteTextView];
NSMutableDictionary *typingAttributes = [[textView typingAttributes] mutableCopy];
[typingAttributes setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
NSLog(@"attributes after: %@", typingAttributes);
textView.attributedText = [[NSAttributedString alloc] initWithString:[textView text] attributes:typingAttributes];
NSLog(@"text view attributes after: %@", [textView typingAttributes]);

End of UITextField typingAttributes example article.