Sunday, June 2, 2013

UITextField attributedText example in Objective C (iOS).


UITextField attributedText

The styled text displayed by the text view.

@property(nonatomic,copy) NSAttributedString *attributedText

Discussion of [UITextField attributedText]
This property is nil by default. Assigning a new value to this property also replaces the value of the text property with the same string data, albeit without any formatting information. In addition, assigning a new a value updates the values in the font, textColor, and other style-related properties so that they reflect the style information starting at location 0 in the attributed string.

UITextField attributedText example.
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"Some String"];
[attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                   value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                   range:(NSRange){0,[attString length]}];

textView.attributedText = attString;

Example of [UITextField attributedText].
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //A context will allow us to not call -attributedText on the textView, which is slow.
    //Keep context up to date
    [self.context replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc] initWithString:text attributes:self.textView.typingAttributes]];

    // […]

    self.textView.scrollEnabled = FALSE;

    [self.context setAttributes:self.defaultStyle range:NSMakeRange(0, self.context.length)];
    [self refresh]; //Runs regex-patterns in the context
    textView.attributedText = self.context;

    self.textView.selectedRange = NSMakeRange(range.location + text.length, 0);
    self.textView.scrollEnabled = TRUE;

    return FALSE;
}

UITextField attributedText example.
NSString *string = @"Hello world";
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.minimumLineHeight = 50.f;
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:string];
[aStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[string length])];
mainTextView.attributedText = aStr;

End of UITextField attributedText example article.