如何将按钮标签传递给 prepareForSegue
Posted
技术标签:
【中文标题】如何将按钮标签传递给 prepareForSegue【英文标题】:How to pass button tag to prepareForSegue 【发布时间】:2013-11-22 12:10:43 【问题描述】:在 Xcode(iPhone 应用程序)中,我以编程方式创建了许多按钮,如下所示:
- (void)viewDidLoad
[super viewDidLoad];
// By Road Button
byRoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
byRoadButton.tag = 3;
byRoadButton.frame = CGRectMake(20, 246, 280.f, 40.f);
UIImage *roadButton = [UIImage imageNamed:@"gettingHereByRoadButton.png"];
[byRoadButton setBackgroundImage:roadButton forState:UIControlStateNormal];
[self.view addSubview:byRoadButton];
[byRoadButton addTarget:self action:@selector(byRoadButtonClicked) forControlEvents:UIControlEventTouchUpInside];
然后我检查哪个按钮被按下:@selector,然后调用 performSegueWithIdentifier。 NSLog 在此处显示正确的按钮标记作为检查。
- (void) byRoadButtonClicked
NSLog(@"Button Pushed Tag Number: %d", byRoadButton.tag);
[self performSegueWithIdentifier:@"gettingHereSegue" sender:self];
但是?思路是把这个标签传给prepareForSegue,根据标签号,把那个按钮关联的信息传给下一个ViewController?
我试过了:
[self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton.tag];
但是得到一个错误提示我试图传递一个 int 而不是一个 id。
在我的 prepareForSegue 中,我有以下内容:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
// ThIS IS WHAT I WANT TO DO - PSEUDO CODE
//int tagNumber = sender;
//if (tagNumber == 3)
//
//Set relevant content of Object here
//
//THIS IS WHAT I CURRENTLY HAVE - NO CHECK FOR TAG
GettingHereContent *gettingHereContent = [[GettingHereContent alloc] init];
gettingHereContent.content = @"This is my custom content based on this buttons click";
GettingHereViewController *vc = (GettingHereViewController *)segue.destinationViewController;
vc.gettingHere = gettingHereContent;
或者任何人都可以提出解决方案或更好的方法吗?
【问题讨论】:
尝试 [self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton];然后在prepareForSegue if (byRoadButton.tagNumber == 3) //这里设置Object的相关内容 是的,非常感谢。在 prepareForSegue 中,我所要做的就是检查按钮是否等于发送者,如下所示: if (byRoadButton == sender) // Do something here 我不必担心标签号来检查按钮点击。再次感谢 【参考方案1】: // try This replace with your code
[self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton];
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender
NSLog(@"%ld",(long)sender.tag);
【讨论】:
【参考方案2】:试试
[self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton];
然后在prepareForSegue
if (sender.tagNumber == 3) //Set relevant content of Object here
【讨论】:
以上是关于如何将按钮标签传递给 prepareForSegue的主要内容,如果未能解决你的问题,请参考以下文章
Swift - PrepareForSegue 无法传递 sender.tag(其他 ViewController 标签中的值为零)
将变量从 tableView 传递给 prepareForSegue?
如何通过单击 TableCell 中的按钮将我的 TableCell 中的标签值传递给 TableViewController? [关闭]
从最初的 View Controller 如何将 acriss 转移到 UITabBarController 并使用 prepareForSegue