Charles Yeung
Charles Yeung

Reputation: 38805

Different section contain different number of rows inside a Table View in iOS

Suppose I have section 1, 2 and 3 in a Table View,

For section 1, it have 3 row
For section 2, it have 5 row
For section 3, it have 1 row

In Objective-c, how can I implement this action in numberOfSectionsInTableView and numberOfRowsInSection? Any additional things I need to do besides these two function? Thanks

Upvotes: 3

Views: 6567

Answers (2)

jbat100
jbat100

Reputation: 16827

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0)
        return 3;

    if (section == 1)
        return 5;

    if (section == 2)
        return 1;

    return 0;

}

You also need to implement at lest the UITableViewDataSource method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Upvotes: 7

Ishu
Ishu

Reputation: 12787

If this is static data then do like this

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

if(section==0)
return 3;
else if(section==1)
return 5;

return 1;
}

and if it is based on data base then make proper data structure and use it for managing.

Upvotes: 8

Related Questions