如何在表视图 iOS 中设置节标题而不重复数据



我有一个表视图,现在我正在初始化表,如下所示,

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [arr count]+1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arr count]+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSUInteger row = [indexPath row];
    if (row == 0) 
    {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        return cell;
    }
    else
    {
        static NSString *CellIdentifier = @"moduleCell";
        MyTableViewCell *cell = (MyTableViewCell*)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
        if (cell == nil) 
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        current = [arr objectAtIndex:indexPath.row-1];
        [cell setCellDetails:arr WithIndex:row-1 withParentView:self];
        return cell;
    }
}

当我在表视图中重复执行此数据时。在我这样做之前,我做到了,

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

这是有效的,但我需要设置标题等部分标题。那么有没有办法在不重复数据的情况下设置节标题呢?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0){//for first section
    }else if(indexPath.section == 1){//for second section
    }
}

您需要实现此方法:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section==0) {
        return "name";
    }else{
        //
    }
}

你需要继续在数组中前进。因此,可以避免在委托方法中进行硬编码。

    NSArray *heading=@[@"Today",@"Yesterday",@"Tomorrow"];

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
            NSString *heading = [heading objectAtIndex:section]; //  
            return heading;
    }
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var cstmView:UIView!
        let lbl:UILabel
        cstmView = UIView()
        cstmView.frame = CGRectMake(0,0,tableView.contentSize.width,70.0)
        let logo:UIImageView = UIImageView();
        logo.image = UIImage(named: "logo_with_lightGrayColor")
        logo.frame = CGRectMake(8.0,10.0,200.0,60.0)
        lbl = UILabel()
        lbl.frame = CGRectMake(8.0,80.0,200.0,20.0)
        lbl.text = "USER NAME"
        lbl.textColor = UIColor.whiteColor()
        lbl.font = UIFont.systemFontOfSize(15.0)
        cstmView .addSubview(logo)
        cstmView.addSubview(lbl)
        return cstmView;
    }

您应该为 tableview 实现自定义标头。

最新更新