Sunday, June 2, 2013

UITextField placeholderRectForBounds example in Objective C (iOS).


UITextField placeholderRectForBounds

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

- (CGRect)placeholderRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The computed drawing rectangle for the placeholder text.

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

If the placeholder string is empty or nil, this method is not called.

UITextField placeholderRectForBounds example.
subclassing UITextField will do the work:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
override the methods:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);//Return your desired x,y position and width,height
}

- (void)drawPlaceholderInRect:(CGRect)rect {
    //draw place holder.
 [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];

}
@end

Example of [UITextField placeholderRectForBounds].
// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
Here's how to override the method:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);
}
@end
However I don't think that's the method you want to override. I think this is what you're looking for:

@implementation
- (void)drawPlaceholderInRect:(CGRect)rect {
    // Your drawing code.
}
@end

UITextField placeholderRectForBounds example.
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    return [self textRectForBounds:bounds];
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return [self textRectForBounds:bounds];
}

End of UITextField placeholderRectForBounds example article.