ustbyjs
ustbyjs

Reputation: 11

Which method is the right one to add subview of UIView

#import <UIKit/UIKit.h>
#import "LCHButton.h"

@interface ParentView: UIView
@property (nonatomic, strong) LCHButton *addStarButton;
@end

In which method should I put [self addSubview:self.addStarButton];?

Upvotes: 1

Views: 757

Answers (2)

Hemang
Hemang

Reputation: 27050

Few things you should correct for best coding practice:

  1. Import LCHButton inside ParentView.m to avoid dependency warnings.

  2. Same for the property, add it inside ParentView.m under your class extension. Things you don't need to access globally should be defined as locally.

e.g.

@Interface ParentView ()
    @property (nonatomic, strong) LCHButton *addStarButton;
@end
  1. Answer to your question:

In init or initWithFrame: method of your ParentView you can it.

e.g.

- (id) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self addSubview:self.addStarButton];
    }
    return self;
}

Upvotes: 2

Riandy
Riandy

Reputation: 372

It depends on where you want to add the subview. Mostly the good practice is to add it in viewDidLoad method so it's only added once. You can add it in viewWillAppear too but remember to remove it in viewDidDisappear, else you will have a lot of subviews.

Upvotes: 0

Related Questions