Sunday, June 2, 2013

UITextField minimumFontSize example in Objective C (iOS).


UITextField minimumFontSize

The size of the smallest permissible font with which to draw the text field’s text.

@property(nonatomic) CGFloat minimumFontSize

Discussion of [UITextField minimumFontSize]
When drawing text that might not fit within the bounding rectangle of the text field, you can use this property to prevent the receiver from reducing the font size to the point where it is no longer legible.

The default value for this property is 0.0. If you enable font adjustment for the text field, you should always increase this value.[UITextField minimumFontSize]

If you are using styled text in iOS 6 or later, assigning a new value to this property causes the minimum font size to be applied to the entirety of the string in the attributedText property. If you want to apply different minimum font sizes to different parts of your string, create a new attributed string with the desired style information and associate it with the text field.

UITextField minimumFontSize example.
textField.font = [UIFont boldSystemFontOfSize:17];
textField.textColor = [UIColor darkGrayColor];
textField.minimumFontSize = 10;
textField.adjustsFontSizeToFitWidth = YES;

Example of [UITextField minimumFontSize].
CGFloat actualFontSize;
[label.text sizeWithFont:label.font
             minFontSize:label.minimumFontSize
          actualFontSize:&actualFontSize
                forWidth:label.bounds.size.width
           lineBreakMode:label.lineBreakMode];

UITextField minimumFontSize example.
- (CGFloat)requiredFontSize
{
    const CGRect  textBounds = [self textRectForBounds: self.frame];
    const CGFloat maxWidth   = textBounds.size.width;

    if( _originalFontSize == -1 ) _originalFontSize = self.font.pointSize;

    UIFont* font     = self.font;
    CGFloat fontSize = _originalFontSize;

    BOOL found = NO;
    do
    {
        if( font.pointSize != fontSize )
        {
            font = [font fontWithSize: fontSize];
        }

        CGSize size = [self.text sizeWithFont: font];
        if( size.width <= maxWidth )
        {
            found = YES;
            break;
        }

        fontSize -= 1.0;
        if( fontSize < self.minimumFontSize )
        {
            break;
        }

    } while( TRUE );

    return( fontSize );
}

End of UITextField minimumFontSize example article.