Thursday, May 30, 2013

UIButton titleRectForContentRect example in Objective C (iOS).

UIButton titleRectForContentRect

Returns the rectangle in which the receiver draws its title.

- (CGRect)titleRectForContentRect:(CGRect)contentRect

Parameters
contentRect
The content rectangle for the receiver.

Return Value of [UIButton titleRectForContentRect]
The rectangle in which the receiver draws its title.

UIButton titleRectForContentRect example.
@implementation UIButtonSubclass

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGRect frame = [super imageRectForContentRect:contentRect];
    frame.origin.x = CGRectGetMaxX(contentRect) - CGRectGetWidth(frame) -  self.imageEdgeInsets.right + self.imageEdgeInsets.left;
    return frame;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGRect frame = [super titleRectForContentRect:contentRect];
    frame.origin.x = CGRectGetMinX(frame) - CGRectGetWidth([self imageRectForContentRect:contentRect]);
    return frame;
}

@end

Example of [UIButton titleRectForContentRect].
@interface PositionTitleButton : UIButton
@property (nonatomic) CGPoint titleOrigin;
@end

@implementation PositionTextButton
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
  contentRect.origin = titleOrigin;
  return contentRect;
}
@end

UIButton titleRectForContentRect example.
tabLog.frame=CGRectMake(10, 400, 32, 53);

    [tabLog titleRectForContentRect:CGRectMake(0, 32, 32, 21)];
    [tabLog imageRectForContentRect:CGRectMake(0, 0, 32, 32)];
    [tabLog setTitle:@"Test" forState:UIControlStateNormal];
    [tabLog setImage:[UIImage imageNamed:@"log.png"] forState:UIControlStateNormal];

End of UIButton titleRectForContentRect example article.