![](/img/trans.png)
[英]selected row in custom cell doesn't pass complete data from segue to another view controller
[英]How to pass data in selected cell to another view controller?
下面的代码将打印在TableView中单击的任何单元格的内容。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.cell[indexPath.row])
}
我想使用打印在另一个ViewController的标签中的结果。
如何从函数中获取字符串值,然后在另一个视图上使用它? 我的想法是使用全局变量,但我需要首先获取字符串值。
首先,创建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)
}
例如,您可以将另一个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
}
您可以像这样更新SecondScreen:
let v = SecondScreen.main
v?.updateUI(string: "yourString")
我也建议您调用异步方法:
DispatchQueue.main.async {
SecondScreen.main?.updateUI(withString : string)
}
我建议您进一步了解单身人士...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.