热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何传递prepareForSegue:对象-HowtopassprepareForSegue:anobject

Ihavemanyannotationsinamapview(withrightCalloutAccessorybuttons).Thebuttonwillperforma

I have many annotations in a mapview (with rightCalloutAccessory buttons). The button will perform a segue from this mapview to a tableview. I want to pass the tableview a different object (that holds data) depending on which callout button was clicked.

我在mapview中有许多注释(带有rightCalloutAccessory按钮)。这个按钮将从这个mapview执行一个segue到一个tableview。我希望根据单击的callout按钮向tableview传递一个不同的对象(它保存数据)。

For example: (totally made up)

例如:(完全化妆)

  • annotation1 (Austin) -> pass data obj 1 (relevant to Austin)
  • 注释1 (Austin) ->通过数据obj 1(与Austin相关)
  • annotation2 (Dallas) -> pass data obj 2 (relevant to Dallas)
  • 注释2 (Dallas) -> pass数据obj2(与Dallas相关)
  • annotation3 (Houston) -> pass data obj 3 and so on... (you get the idea)
  • 注释3 (Houston) ->通过数据obj3等等…(你懂的)

I am able to detect which callout button was clicked.

我可以检测哪个callout按钮被单击。

I'm using prepareForSegue: to pass the data obj to the destination ViewController. Since I cannot make this call take an extra argument for the data obj I require, what are some elegant ways to achieve the same effect (dynamic data obj)?

我正在使用prepareForSegue:将数据obj传递给目标视图控制器。由于我不能对我需要的数据obj进行额外的参数调用,那么有什么优雅的方法可以达到相同的效果(动态数据obj)?

Any tip would be appreciated.

如有任何提示,我们将不胜感激。

10 个解决方案

#1


658  

Simply grab a reference to the target view controller in prepareForSegue: method and pass any objects you need to there. Here's an example...

只需在prepareForSegue:方法中获取对目标视图控制器的引用,并将需要的任何对象传递到那里。这里有一个例子……

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
    {
        // Get reference to the destination view controller
        YourViewController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        [vc setMyObjectHere:object];
    }
}

REVISION: You can also use performSegueWithIdentifier:sender: method to activate the transition to a new view based on a selection or button press.

修订:您还可以使用performSegueWithIdentifier:sender:方法根据选择或按下按钮激活到新视图的转换。

For instance, consider I had two view controllers. The first contains three buttons and the second needs to know which of those buttons has been pressed before the transition. You could wire the buttons up to an IBAction in your code which uses performSegueWithIdentifier: method, like this...

例如,假设我有两个视图控制器。第一个包含三个按钮,第二个需要知道在转换之前按了哪些按钮。您可以将这些按钮连接到代码中的IBAction,它使用performSegueWithIdentifier: method,如下所示…

// When any of my buttons are pressed, push the next view
- (IBAction)buttonPressed:(id)sender
{
    [self performSegueWithIdentifier:@"MySegue" sender:sender];
}

// This will get called too before the view appears
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"MySegue"]) {

        // Get destination view
        SecondView *vc = [segue destinationViewController];

        // Get button tag number (or do whatever you need to do here, based on your object
        NSInteger tagIndex = [(UIButton *)sender tag];

        // Pass the information to your destination view
        [vc setSelectedButton:tagIndex];
    }
}

EDIT: The demo application I originally attached is now six years old, so I've removed it to avoid any confusion.

编辑:我最初附加的演示应用程序现在已经有6年的历史了,所以我删除了它以避免任何混淆。

#2


81  

The accepted answer is not the best way of doing this, because it creates an unnecessary compile-time dependency between two view controllers. Here's how you can do it without caring about the type of the destination view controller:

公认的答案不是最好的方法,因为它在两个视图控制器之间创建了不必要的编译时依赖。以下是如何在不考虑目标视图控制器类型的情况下完成的:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController respondsToSelector:@selector(setMyData:)]) {
        [segue.destinationViewController performSelector:@selector(setMyData:) 
                                              withObject:myData];
    } 
}

So as long as your destination view controller declares a public property, e.g.:

因此,只要您的目标视图控制器声明公共属性,例如:

@property (nonatomic, strong) MyData *myData;

you can set this property in the previous view controller as I described above.

如前所述,可以在前面的视图控制器中设置此属性。

#3


19  

In Swift I would do something like that:

在《Swift》中,我会这样做:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destinationViewController as? YourViewController {
        yourVC.yourData = self.someData
    }
}

#4


16  

I have a sender class, like this

我有一个sender类,像这样

@class MyEntry;

@interface MySenderEntry : NSObject
@property (strong, nonatomic) MyEntry *entry;
@end

@implementation MySenderEntry
@end

I use this sender class for passing objects to prepareForSeque:sender:

我使用这个sender类将对象传递给prepareForSeque:sender:

-(void)didSelectItemAtIndexPath:(NSIndexPath*)indexPath
{
    MySenderEntry *sender = [MySenderEntry new];
    sender.entry = [_entries objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:SEGUE_IDENTIFIER_SHOW_ENTRY sender:sender];
}

-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_SHOW_ENTRY]) {
        NSAssert([sender isKindOfClass:[MySenderEntry class]], @"MySenderEntry");
        MySenderEntry *senderEntry = (MySenderEntry*)sender;
        MyEntry *entry = senderEntry.entry;
        NSParameterAssert(entry);

        [segue destinationViewController].delegate = self;
        [segue destinationViewController].entry = entry;
        return;
    }

    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_HISTORY]) {
        // ...
        return;
    }

    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_FAVORITE]) {
        // ...
        return;
    }
}

#5


11  

I came across this question when I was trying to learn how to pass data from one View Controller to another. I need something visual to help me learn though, so this answer is a supplement to the others already here. It is a little more general than the original question but it can be adapted to work.

我在学习如何将数据从一个视图控制器传递到另一个视图控制器时遇到了这个问题。我需要一些视觉上的东西来帮助我学习,所以这个答案是对其他已经存在的答案的补充。它比最初的问题更一般一些,但是它可以用于工作。

This basic example works like this:

这个基本示例如下所示:

enter image description here

The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

其思想是将字符串从第一个视图控制器中的文本字段传递给第二个视图控制器中的标签。

First View Controller
import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    // This function is called before the segue
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // get a reference to the second view controller
        let secOndViewController= segue.destinationViewController as! SecondViewController

        // set a variable in the second view controller with the String to pass
        secondViewController.receivedString = textField.text!
    }

}
Second View Controller
import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Used the text from the First View Controller to set the label
        label.text = receivedString
    }

}
Remember to
  • Make the segue by control clicking on the button and draging it over to the Second View Controller.
  • 通过控件单击按钮并将其拖放到第二个视图控制器来进行segue。
  • Hook up the outlets for the UITextField and the UILabel.
  • 连接UITextField和UILabel的outlet。
  • Set the first and second View Controllers to the appropriate Swift files in IB.
  • 将第一和第二视图控制器设置为IB中相应的Swift文件。
Source

How to send data through segue (swift) (YouTube tutorial)

如何通过segue (swift)发送数据(YouTube教程)

See also

View Controllers: Passing data forward and passing data back (fuller answer)

视图控制器:向前传递数据并返回数据(更完整的答案)

#6


4  

I've implemented a library with a category on UIViewController that simplifies this operation. Basically, you set the parameters you want to pass over in a NSDictionary associated to the UI item that is performing the segue. It works with manual segues too.

我在UIViewController中实现了一个类的库,它简化了这个操作。基本上,您设置了要在与执行segue的UI项相关的NSDictionary中传递的参数。它也适用于手动segue。

For example, you can do

例如,你可以这样做

[self performSegueWithIdentifier:@"yourIdentifier" parameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

for a manual segue or create a button with a segue and use

用于手动segue或使用segue创建按钮

[button setSegueParameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

If destination view controller is not key-value coding compliant for a key, nothing happens. It works with key-values too (useful for unwind segues). Check it out here https://github.com/stefanomondino/SMQuickSegue

如果目标视图控制器不符合键值编码,则不会发生任何事情。它也适用于键值(对展开segue很有用)。在这里查看https://github.com/stefanomondino/SMQuickSegue

#7


4  

For Swift use this,

斯威夫特用这个,

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var segueID = segue.identifier

    if(segueID! == "yourSegueName"){

        var yourVC:YourViewCOntroller= segue.destinationViewController as YourViewController

        yourVC.objectOnYourVC= setObjectValueHere!

    }
}

#8


2  

My solution is similar.

我的解决方案是相似的。

// In destination class: 
var AddressString:String = String()

// In segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if (segue.identifier == "seguetobiddetailpagefromleadbidder")
    {
        let secOndViewController= segue.destinationViewController as! BidDetailPage
        secondViewController.AddressString = pr.address as String
    }
}

#9


0  

I used this solution so that I could keep the invocation of the segue and the data communication within the same function:

我使用了这个解决方案,这样我就可以在同一个函数中调用segue和数据通信:

private var segueCompletion : ((UIStoryboardSegue, Any?) -> Void)?

func performSegue(withIdentifier identifier: String, sender: Any?, completion: @escaping (UIStoryboardSegue, Any?) -> Void) {
    self.segueCompletion = completion;
    self.performSegue(withIdentifier: identifier, sender: sender);
    self.segueCompletion = nil
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    self.segueCompletion?(segue, sender)
}

A use case would be something like:

一个用例应该是这样的:

func showData(id : Int){
    someService.loadSomeData(id: id) {
        data in
        self.performSegue(withIdentifier: "showData", sender: self) {
            storyboard, sender in
            let dataView = storyboard.destination as! DataView
            dataView.data = data
        }
    }
}

This seems to work for me, however, I'm not 100% sure that the perform and prepare functions are always executed on the same thread.

但是,这似乎对我来说是有效的,但是,我不能百分之百地确定执行和准备函数总是在同一个线程上执行。

#10


0  

Just use this function.

使用这个函数。

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let index = CategorytableView.indexPathForSelectedRow
    let indexNumber = index?.row
    let VC = segue.destination as! DestinationViewController
   VC.value = self.data

}

推荐阅读
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 深入解析Android自定义View面试题
    本文探讨了Android Launcher开发中自定义View的重要性,并通过一道经典的面试题,帮助开发者更好地理解自定义View的实现细节。文章不仅涵盖了基础知识,还提供了实际操作建议。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文基于刘洪波老师的《英文词根词缀精讲》,深入探讨了多个重要词根词缀的起源及其相关词汇,帮助读者更好地理解和记忆英语单词。 ... [详细]
  • c# – UWP:BrightnessOverride StartOverride逻辑 ... [详细]
  • Android 渐变圆环加载控件实现
    本文介绍了如何在 Android 中创建一个自定义的渐变圆环加载控件,该控件已在多个知名应用中使用。我们将详细探讨其工作原理和实现方法。 ... [详细]
  • 在使用 DataGridView 时,如果在当前单元格中输入内容但光标未移开,点击保存按钮后,输入的内容可能无法保存。只有当光标离开单元格后,才能成功保存数据。本文将探讨如何通过调用 DataGridView 的内置方法解决此问题。 ... [详细]
  • 本文介绍如何在 Android 中通过代码模拟用户的点击和滑动操作,包括参数说明、事件生成及处理逻辑。详细解析了视图(View)对象、坐标偏移量以及不同类型的滑动方式。 ... [详细]
  • Python 异步编程:深入理解 asyncio 库(上)
    本文介绍了 Python 3.4 版本引入的标准库 asyncio,该库为异步 IO 提供了强大的支持。我们将探讨为什么需要 asyncio,以及它如何简化并发编程的复杂性,并详细介绍其核心概念和使用方法。 ... [详细]
  • 本文详细探讨了KMP算法中next数组的构建及其应用,重点分析了未改良和改良后的next数组在字符串匹配中的作用。通过具体实例和代码实现,帮助读者更好地理解KMP算法的核心原理。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • Android LED 数字字体的应用与实现
    本文介绍了一种适用于 Android 应用的 LED 数字字体(digital font),并详细描述了其在 UI 设计中的应用场景及其实现方法。这种字体常用于视频、广告倒计时等场景,能够增强视觉效果。 ... [详细]
author-avatar
手机用户2502878261
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有