[英]How to pass data in selected cell to another view controller?
The piece of code below prints the content of whichever cell is clicked on in my TableView. 下面的代码将打印在TableView中单击的任何单元格的内容。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.cell[indexPath.row])
}
I want to use the result that is printed in a label on another ViewController. 我想使用打印在另一个ViewController的标签中的结果。
How do I get the string value from the function and then use it on on the other view? 如何从函数中获取字符串值,然后在另一个视图上使用它? My thought is to use a global variable but I need to get the string value out first.
我的想法是使用全局变量,但我需要首先获取字符串值。
At first, when you create a tableView
, you have to collect data ( string here) of cells in an array or another data collection. 首先,创建
tableView
,必须收集数组或其他数据集合中单元格的数据(此处为字符串 )。 And you can get a needed data ( strings ) with indexPath
variable in the method didSelectRowAt
. 您可以在
didSelectRowAt
方法中使用indexPath
变量获取所需的数据( 字符串 )。 And you can pass the string to another ViewController
(let use SecondViewController
) with several ways. 您可以通过几种方式将字符串传递给另一个
ViewController
(让我们使用SecondViewController
)。
Here is an example: 这是一个例子:
// 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
}
Don't forget update in async DispatchQueue: 不要忘记在异步DispatchQueue中进行更新:
DispatchQueue.main.async {
SecondViewController.main?.updateUI(withString : string)
}
For example, You can use simple organization of a singleton of another ViewController ( SecondScreen
) with var main
(in case, as usual, when SecondScreen
inited via a Storyboard): 例如,您可以将另一个ViewController(
SecondScreen
)的单例与var main
一起使用的简单组织( SecondScreen
万一,通常情况下,通过Storyboard 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
}
And you can update your SecondScreen like this: 您可以像这样更新SecondScreen:
let v = SecondScreen.main
v?.updateUI(string: "yourString")
Also I recommend you to call method async: 我也建议您调用异步方法:
DispatchQueue.main.async {
SecondScreen.main?.updateUI(withString : string)
}
I suggest you to learn more about singletons... 我建议您进一步了解单身人士...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.