将单元格标签或标题传递给另一个视图控制器

时间:2014-07-14 16:31:48

标签: ios

我有5行/单元格的tableview控制器。我只是使用NSArray为这些单元格分配文本/标题。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
  *)indexPath       
  {
  static NSString *cellIdentifier=@"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier     forIndexPath:indexPath];
cell.textLabel.text = [title objectAtIndex:indexPath.row];
return cell;
  }

现在我希望当我选择特定单元格时,特定单元格标题/文本将传递给另一个另一个视图控制器。所以我可以像这样使用那个文本

 if(cell.text=="this"){
  ...do this
  }

有人可以帮助我或给我更好的解决方案吗?

4 个答案:

答案 0 :(得分:0)

你想在didSelectRowAtIndexPath方法中这样做。因此,当他们选择一行时,您将推送下一个视图控制器,并使用cell.label.text作为标题初始化该viewController。基本上它看起来像这样:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NewViewController *newView = [[NewViewController alloc] init];


[self.navigationController pushViewController:newView animated:YES];
UILabel * myLabel = (UILabel *) [newView.view viewWithTag:1];
myLabel.text = [title objectAtIndex:indexPath.row];
}

假设您希望新视图中的标签与您单击的单元格的文本相等。您必须在界面构建器中将此标签的标记设置为1。

答案 1 :(得分:0)

Apple在那里Table View Programming Guide for iOS解释了如何将数据从一个视图控制器移动到另一个视图控制器。

我简短地执行:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

查看上面的链接和第3-1节“将数据传递到目标视图控制器”。

答案 2 :(得分:0)

首先,在SecondViewController中创建一个NSString属性。它应该是这样的: @property (nonatomic, retain) NSString *lblText; (将您喜欢的任何名称添加到变量中)。

我假设您正在使用故事板。如果没有,那么请像我们使用XIB文件一样进行导航。

现在,来到第一个视图控制器。

创建UILable属性以在tableview行上设置文本。它还可用于将值传递给下一个viewcontroller。

@property(nonatomic,retain)UILabel * lbl;

在第一个视图中,控制器的实现文件在UITableView的委托方法中编写以下代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
  *)indexPath 
 {
    lbl = [cell objectAtIndex:indexPath.row];
}

现在,使用UITableview -didSelectRowAtIndexpath的委托方法。并在其中编写以下代码。

{
    SecondViewController *vc = (SecondViewController *) [self.storyboard instantiateViewController:@"SecondViewController"];
    vc.lblText = lbl.text;
    [self.navigationController pushViewController:vc animated:YES];
}

现在。您在变量lblText中有标签值,因此您可以在第二个视图中的任何位置使用它(即新视图)。

答案 3 :(得分:0)

在另一个viewController中你必须添加一个属性

@property (nonatomic, copy) NSString *text;
在tableViewController中使用实现此方法的5个单元格

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self performSegueWithIdentifier:@"Identifier" sender:tableView];
}

和这个

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

  if ([segue.identifier isEqualToString:@"Identifier"]) {

      UITableView *tableView = (UITableView *)sender;

    // here is the other ViewController init
      ViewController *vc =(ViewController*)segue.destinationViewController;

      vc.text = [self.title objectAtIndex:[tableView indexPathForSelectedRow].row];      
  }

}

在另一个ViewController中,您可以执行类似

的操作
- (void)viewDidLoad
{
   [super viewDidLoad];
   if ([text isEqualsToString:@"game"]){

    Nslog(@"New Game");

   }

}

希望它对你有用

相关问题