PruitIgoe
PruitIgoe

Reputation: 6384

iOS: Subclassing UILabel and updating its indents

I have an app which contains a pretty large form. I subclassed UILabel so I could have consistency in the form labels. However, a few of the labels are going to be section dividers with a background color and they'll require an indent.

I know I can over ride the UILabel's indent setting when it instantiates by using this code:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

but that'll add insets to all of the labels. Not what I want.

So what I did was wrote a custom method:

- (void) makeInsets
{
    CGRect rect = self.frame;

    if (hasInset) {
        UIEdgeInsets insets = {0, 5, 0, 5};
        return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
    } else {
        UIEdgeInsets insets = {0, 0, 0, 0};
        return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
    }
}

Problem with that is it happens after the UILabel is drawn. I tried [UILabelSubclass setNeedsDisplay:YES] but get a "No visible interface" error for the setNeedsDisplay method. Is there a way I can override the existing inset with my custom ones?

Upvotes: 0

Views: 971

Answers (2)

user577537
user577537

Reputation:

You get a "No visible interface" error with setNeedsDisplay because the method doesn't take an argument. You should just write:

[subclassedLabelInstance setNeedsDisplay];

and that error should go away. It might also solve the issue.

Upvotes: 2

jerrylroberts
jerrylroberts

Reputation: 3454

Since you're subclassing it... can't you just add a boolean property to indicate whether or not to indent?

.h file

@property BOOL indentText;

.m file

- (id) initWithIndent:(BOOL)indent {

    if((self = [super init])) {
        self.indentText = indent;
    }

    return self;
}

- (void)drawTextInRect:(CGRect)rect {

    if( self.indentText ) {
        UIEdgeInsets insets = {0, 5, 0, 5};
        return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
    }
}

If you're planning on having a lot of customizations then you could pass some sort of style constant in when you're create the label to indicate how to mark it up... but if all you plan to do is this then I would just add a simple property to toggle it on.

Upvotes: 1

Related Questions