I am designing a Custom UIView for my app.

The UIView will comprise of below components:

  1. UISearchbar
  2. UITableView

My initialiser is below:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectZero];
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero];
        _tableView.dataSource = self;
        [super addSubView:_searchBar];
        [super addSubView:_tableView];
        // Initialization code
    }
    return self;
}

I am planning to set the frame of the _searchBar and _tableView in layoutsubviews method.

But I think think the way I have added the _tableView to super is wrong. Because the moment the _tableView is added to subview the data source methods of the _tableView will be triggered. And this happens even before the creation of the custom class itself.

Is this a correct design?

Can I add just _tableView alone in layoutSubviews as in below manner?

-(void)layoutSubViews{

//Adjust frame 
[_tableView removeFromSuperView];
[self addSubView:_tableView];

}
有帮助吗?

解决方案

You shouldn't be assigning the UITableViewDataSource in the view. It should be assigned in the ViewController.

You're right. There is no restriction on it. But your question is about design. Imagine something like this:

@implementation CustomViewController

- (void)loadView {
    customView = [[CustomView alloc] initWithFrame:CGRectZero];

    customView.tableView.dataSource = self;
    customView.tableView.delegate = self;
}

With a ViewController, you can control when you initialize your custom view and control when its tableView loads the data. While you can certainly put all of this code into your customView, you will be running into problems much worse than the one you are asking about now.

其他提示

You should definitely add it in init, because layout sub-views will get called each time you view will resize and will need to re-layout its sub-views. Layout subviews method is strictly use as a callback telling you that your view will layout, and is used as an override point for any additional layout you wish to make. Also, as an additional note, it's not good design adding the view using super.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top