开发者

What is the proper way of hard-coding sections in a UITableView?

开发者 https://www.devze.com 2022-12-31 19:40 出处:网络
I have a UITableView with 3 sections that are hard coded. Everything is working fine, but I am not sure if I am doing it correctly.

I have a UITableView with 3 sections that are hard coded. Everything is working fine, but I am not sure if I am doing it correctly.

Define number of rows in section:

- (NSInteger)tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows;

        //Bio Section
        if(section == 0){
            rows = 2;
        }
        //Profile section
        else if(section == 1){
            rows = 5;
        }
        //Count section
        else if(section == 2){
            rows = 3;
        }
    }  

    return rows;
}

Here is where I build my cells:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tblView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewC开发者_运维知识库ell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.numberOfLines = 5;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:(10.0)];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;

    if ([self.message_source isEqualToString:@"default"]) {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                cell.textLabel.text = [Utils formatMessage:[NSString stringWithFormat: @"%@", mySTUser.bio]];
                cell.detailTextLabel.text = nil;
            }
            else if(indexPath.row == 1){
                cell.textLabel.text = [NSString stringWithFormat: @"%@", mySTUser.website];
                cell.detailTextLabel.text = nil;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
} //more code exists, but you get the point...

Now I define my number of sections

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

Is this the proper way of hard-coding my UITableView? Will I run into any issues when cells are reused?


You might consider using a switch-case tree with an enumerated type, to replace the if conditionals that test for various hard-coded integers. This blog post explains this option in more detail. Using switch-case with your table view delegate methods will make your code much more readable and flexible. Otherwise, your reuse code looks correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消