选择单元格时如何将特定值传递给该单元格?

How to pass specific value to a cell when that cell is selected?

简而言之,如何在索引路径的 didselect 行中调用 performforsegue 方法。我有一个数组,这个数组是 tableView

的内容
`let array = ["USD","Inr", "AUD", "AED"]` 

我有这个数组的值

let valueUSD = "65"
let valueInr = "10"
let valueAUD = "70"
let valueAED = "20"
 

我有另一个 viewController,带有可选字符串和标签,在我调用的 viewdidload 上

label.text = optionalstring //just a pseudocode but you get the idea

现在问题来了,当用户选择 USD 时,我希望可选字符串采用 valueUSD 变量的值,当他选择 INR 时,它应该采用 valueInr 变量值等等,以便目标视图控制器将显示此值,我不知道如何实现这一点,如何获取所选 indexpath.row 并基于该值如何设置值,例如

if indexpath.row == 0

`destinationViewController.optionalString = valueUSD`

感谢您的关注。

您应该将数据存储在自定义结构类型的数组中:

let array = [
    MyData(name: "USD", number: "65"),
    MyData(name: "Inr", number: "10"),
    MyData(name: "AUD", number: "70"),
    MyData(name: "AED", number: "20"),
]

其中 MyData 是这样的:

struct MyData { // please give this a better name based on the data that you are working with!
    let name: String
    let number: String
}

您可能需要更改 cellForRowAt 方法以将单元格的标签文本设置为 array[indexPath.row].name 而不是 array[indexPath.row]

didSelectRowAt中:

let selectedData = array[indexPath.row].number
performSegue(withIdentifier: "insert your segue identifier here", sender: selectedData)

然后,覆盖 prepare(for:sender:):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? TypeOfTheDestinationVC,
        let number = sender as? String {
        vc.optionalString = number
    }
}