在UITableView中对部分进行硬编码的正确方法是什么?

时间:2010-05-25 16:37:11

标签: iphone objective-c cocoa-touch xcode uitableview

我有一个UITableView有3个硬编码的部分。一切都很好,但我不确定我是否正确地做到了。

定义部分中的行数:

- (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;
}

这是我构建我的细胞的地方:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tblView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell 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...

现在我定义我的部分数量

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

这是硬编码UITableView的正确方法吗?重复使用单元格时会遇到任何问题吗?

1 个答案:

答案 0 :(得分:3)

您可以考虑使用带有enumerated typeswitch-case树来替换测试各种硬编码整数的if条件。 This blog post更详细地解释了此选项。在表格视图中使用switch-case委托方法将使您的代码更具可读性和灵活性。否则,您的重用代码看起来是正确的。

相关问题