UITableView set background color

后端 未结 8 1509
离开以前
离开以前 2020-12-24 02:51

I change the background color of the UITableViewCells in the tableView:cellForRowAtIndexPath method

    if(indexPath.row % 2 == 0){
        cell.bac         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 03:28

    If you want the cell background color to continue to alternate, then you need to lie about how many rows are in the table. Specifically, in tableView:numberOfRowsInSection you need to always return a number that will fill the screen, and in tableView:cellForRowAtIndexPath, return a blank cell for rows that are beyond the end of the table. The following code demonstrates how to do this, assuming that self.dataArray is an NSArray of NSStrings.

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if ( self.dataArray.count < 10 )
            return( 10 );
        else
            return( self.dataArray.count );
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SimpleCell"];
    
        if ( indexPath.row % 2 == 0 )
            cell.backgroundColor = [UIColor orangeColor];
        else
            cell.backgroundColor = [UIColor redColor];
    
        if ( indexPath.row < self.dataArray.count )
            cell.textLabel.text = self.dataArray[indexPath.row];
        else
            cell.textLabel.text = nil;
    
        return cell;
    }
    

提交回复
热议问题