Hema
Hema

Reputation: 947

UITableView with fixed 5 rows

I'm working on an app where I need to show 5 rows of data all the time. The data for the rows comes from a NSArray of strings. The NSArray can be empty or can contain a max of 5 elements. I wanted to force the UITableView to have 5 rows displayed all the time. I tried it and when the NSArray has just 1 element, iOS throws a exception due to the fact I have defined 5 rows (numberOfRowsInSection). How do I make the UITableView to display 5 rows (Grouped, single line) all the time without raising a exception?. Also, how do I center the section header? I'm using titleForHeaderInSection method.

Upvotes: 0

Views: 177

Answers (2)

Denis
Denis

Reputation: 358

  1. To display 5 rows your should to return constant 5 in the numberOfRowsInSection and in the method cellForRowAtIndexPath generate your empty cell if indexPath.row >= [array count].
  2. To display header in the center use

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

Upvotes: 0

Rohan Agarwal
Rohan Agarwal

Reputation: 2187

In your cellForRowAtIndexPath, you need to implement logic that's based on the size of your NSArray of strings.

Find the total number of strings using [NSArray count] . Then, check if indexPath.row is less than [NSArray count] and use your standard implementation where you get the string from the array using indexPath.row as your index. If indexPath.row is not less than [NSArray count], then you can just keep the cell empty (and not try to retrieve anything from your array). Then you won't have that exception.

For the title header, does this work? https://discussions.apple.com/thread/2539133?start=0&tstart=0

Replace UITextAlignmentCenter with NSTextAlignmentCenter.

It works around your issue by using viewForHeaderInSection and returning a centered UILabel.

Upvotes: 1

Related Questions