how can i set two colors to alternative row in two different sections in UITableView in iphone

佐手、 提交于 2020-01-06 06:45:57

问题


I have a UITableView with two sections, section 0 contains 1 row and section 1 contains two rows. My Question how can i set two colors to alternative row.I tried the fallowing way but section0 first row and section1 first row shows same same color.

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

{

static NSString *cellIdentifier=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell==nil)
    {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
 if(indexPath.row%2==0)
    {
        cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Light.png"]];


    }
    else
    {
        cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Dark.png"]];


    }
return cell;
}

回答1:


Use tableView:willDisplayCell: and set the background colour/image there.




回答2:


Hope this helps...

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

{

    static NSString *cellIdentifier=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell==nil)
    {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    int cellCount = 0;
    for(int sections=0;sections<indexPath.section;sections++)
    {
        cellCount = cellCount+[self tableView:self.tableView numberOfRowsInSection:sections];
    }
    cellCount = cellCount + indexPath.row
    if(cellCount%2==0)
    {
        cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Light.png"]];
    }
    else
    {
        cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Dark.png"]];
    }

return cell;
}


来源:https://stackoverflow.com/questions/13340722/how-can-i-set-two-colors-to-alternative-row-in-two-different-sections-in-uitable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!