在UITableView中更改UITableViewCells

时间:2013-06-24 21:07:47

标签: ios objective-c uitableview

我是UITableViews的新手,我对这个话题不太了解。

我在同一个视图中有两个按钮,但不在表中,用于控制UITableViewCells之间的切换,当按下一个按钮然后设置一个布尔值来加载特定的Cell。

  • 如果单击按钮1,则会显示包含CellType1的表。
  • 如果单击按钮2,则会显示包含CellType2的表。

我的目标是使用相同的表格。但我不知道从哪里开始。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
if (clickButton1 == true)
    {
        clickButton1 *cell = (clickButton1*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
        if (cell == nil) {
            //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CellType1" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        cell.name.text =  @"Trial";
        return cell;
    }
    else if (clickButton2 == true)
    {
        clickButton2 *cell = (clickButton2*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
        if (cell == nil) {
            //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CellType2" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        //cell.name.text =  @"Trial";
        return cell;
    } else

我认为这段代码不是最好的。但是我在这一点上输了。 提前谢谢!

1 个答案:

答案 0 :(得分:2)

使用像这样的教程示例......

//3</pre>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section        {
return [self.tweetsArray count];
}

//4
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 //5
 static NSString *cellIdentifier = @"SettingsCell";

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//6
NSString *tweet = [self.tweetsArray objectAtIndex:indexPath.row];
//7
[cell.textLabel setText:tweet];
[cell.detailTextLabel setText:@"via Codigator"];
return cell;
}

如果您有两个数组用于self.tweetArray1和self.tweetArray2等项目,则可以将此代码更改为

//3</pre>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section      {

int i = buttonNumberClicked;
return [self.tweetsArray[i] count];
}

  //4
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:   (NSIndexPath *)indexPath {
//5

int i = buttonNumberClicked;

static NSString *cellIdentifier = @"SettingsCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//6
NSString *tweet = [self.tweetsArray[i] objectAtIndex:indexPath.row];
//7
[cell.textLabel setText:tweet];
[cell.detailTextLabel setText:@"via Codigator"];
return cell;
}

并设置按钮的ibactions将变量/ int buttonNumberClicked更改为1或2,具体取决于按下的和[tableView reloadData];在ibaction内部,希望这有帮助。