【问题标题】:How to pass data in selected cell to another view controller?如何将选定单元格中的数据传递给另一个视图控制器?
【发布时间】:2018-12-03 15:22:33
【问题描述】:

下面的代码会打印在我的 TableView 中单击的任何单元格的内容。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)  {
    print(self.cell[indexPath.row])
}

我想使用打印在另一个 ViewController 上的标签中的结果。

如何从函数中获取字符串值,然后在另一个视图上使用它?我的想法是使用全局变量,但我需要先获取字符串值。

【问题讨论】:

标签: ios swift label global-variables tableview


【解决方案1】:

例如,您可以使用带有 var main 的另一个 ViewController (SecondScreen) 的单例的简单组织(以防万一,当 SecondScreen 通过情节提要启动时) :

class SecondScreen : UIViewController {
    // 1. add this var
    static var main : SecondScreen? = nil

    // 2. Your some UI element
    @IBOutlet weak var textButton: UIButton!

    // 3. add this method
    func updateUI(string : String) {
        textButton.setTitle(string, for: .normal)
    }

    // 4. setting a var
    override func viewDidLoad() {
        if SecondScreen.main == nil {
            SecondScreen.main = self
        }
    }

    // ... another your and standard methods
}

您可以像这样更新您的 SecondScreen:

    let v = SecondScreen.main
    v?.updateUI(string: "yourString")

另外我建议你调用异步方法:

DispatchQueue.main.async {
    SecondScreen.main?.updateUI(withString : string)
}

我建议你了解更多关于单例...

【讨论】:

    【解决方案2】:

    首先,当您创建tableView 时,您必须收集数组或其他数据集合中单元格的数据(此处为字符串)。您可以通过 didSelectRowAt 方法中的 indexPath 变量获取所需的数据(字符串)。您可以通过多种方式将字符串传递给另一个ViewController(让我们使用SecondViewController)。

    这是一个例子:

    // declaration an array of your strings
    var array : [String] = ["First", "Second", "Third", ...]
    ...
    // getting a string from method:
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)  {
    let string = array[indexPath.row]
    print(string)
    // next, for example, you need to pass the string to a singleton SecondViewController with static var **main**:
    SecondViewController.main?.neededString = string
    }
    

    不要忘记异步 DispatchQueue 中的更新:

    DispatchQueue.main.async {
        SecondViewController.main?.updateUI(withString : string)
    }
    

    【讨论】:

    • 谢谢!这是可行的,但是我必须转到另一个页面,然后在第二个视图控制器更新之前返回。我将如何强制第二个视图控制器实时更新
    • 试试这个方法: 1)你必须在某个变量中有第二个 ViewController 的实例(第二个 VC 可以是子视图或超级视图的控制器)。你可以调用第二个VC的方法,在那里你可以改变它的UI。 2)如果你没有实例,你可以用你的字符串初始化第二个VC。
    • 第二个视图实际上是一个外部监视器,其想法是当单击一个单元格时,它会在外部监视器上的标签中显示该单元格的值。我对 swift 很陌生,但我基本上只需要刷新外部视图。对吗?
    • 您可以学习和使用多种技术:1. 单例,2. 通知中心并等待更新,3. 使用委托和协议的方法,4. 使用块,5 . 使用计时器并监听 UserDefaults(疯狂,但有效)。这里描述了一些方法:link
    • 我收到一条错误消息,提示 SecondScreen 没有成员 'main'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多