Sunday, June 2, 2013

UITextField textRectForBounds example in Objective C (iOS).


UITextField textRectForBounds

Returns the drawing rectangle for the text field’s text.

- (CGRect)textRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The computed drawing rectangle for the label’s text.

Discussion of [UITextField textRectForBounds]
You should not call this method directly. If you want to customize the drawing rectangle for the text, you can override this method and return a different rectangle.

The default implementation of this method returns a rectangle that is derived from the control’s original bounds, but which does not include the area occupied by the receiver’s border or overlay views.

UITextField textRectForBounds example.
textField.bounds = [self editingRectForBounds:textField.bounds];
textField.bounds = [self textRectForBounds:textField.bounds];

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect inset = CGRectMake(bounds.origin.x + 10, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    return inset;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect inset = CGRectMake(bounds.origin.x + 10, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    return inset;
}

Example of [UITextField textRectForBounds].
@interface UITextField (myCustomTextField)

@end

@implementation UITextField (myCustomTextField)

- (CGRect)textRectForBounds:(CGRect)bounds {

    return CGRectInset(bounds, 10, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

@end

UITextField textRectForBounds example.
Example of subclassing the UITextField:

- (CGRect)textRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

End of UITextField textRectForBounds example article.