Question

I have subclassed a UITextField and trying to add a subview by calling [self.superView addSubview:newView] but this is not working and self.superview.class returns null.

How can one add a subview to the superView

The view is showing on the screen and done using Storyboard

@interface NewTextField : UITextField <UITextFieldDelegate>


@end

and then

@implementation MBTextField


- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self addWhiteLine]; // here im adding a view 
    }
    return self;
}


- (void)addWhiteLine{

    UIView *div = [UIView new];
    div.frame = CGRectMake(self.frame.origin.x,
                           self.frame.origin.y + self.frame.size.height+borderWidth,
                           self.frame.size.width,
                           borderWidth);

    div.backgroundColor = [borderColor colorWithAlphaComponent:0.3f];
    [self.superview addSubview:div];

}

Solution: accepted answer and comments by @mackworth. Frame of the view had to be changed to following.

    div.frame = CGRectMake(0,
                           self.frame.size.height - borderWidth,
                           self.frame.size.width,
                           borderWidth);
Was it helpful?

Solution

If self.superview is nil, then at the time addWhiteLine is being called, self hasn't been added to the view hierarchy yet. This actually makes sense given that you're calling it from the initWithCoder. Whoever's loading this view has to alloc/init before adding it to a superview. As a fix, why add to self.superview, shouldn't you add to self instead?

Edit: As discussed in comments, another problem is that the line is being drawn outside the frame, so it should be self.frame.origin.y + self.frame.size.height-borderWidth instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top