【问题标题】:How to get the user selected values from array in UITableView and pass that values to server如何从 UITableView 中的数组中获取用户选择的值并将该值传递给服务器
【发布时间】:2017-11-24 09:27:14
【问题描述】:

我有两个字典数组

    1. Array of categories

        [{
          "Category_ID": "1",
          "Category_en": "Event1",
        }, 
        {
          "Category_ID": "4",
          "Category_en": "Event4",
        },
        {
          "Category_ID": "9",
          "Category_en": "Event9",
        }]

    2.Array of cities
        [{
          "City_id": "1",
          "City_name": "Place1",
        }, 
        {
          "City_id": "2",
          "City_name": "Place2",
        },
        {
          "City_id": "4",
          "City_name": "Place4",
        }]

我在两个 tableViews 中显示这些数组中的值,用户可以选择多个项目,表示他们想要的城市和类别。如何获取用户选择的城市、类别并将该 id 值传递给 url 以从服务器获取结果

如果我通过此方法将选定的行作为数组获取,我如何将来自城市和类别的相应 id 附加到 url

let list = tableView.indexPathsForSelectedRows() as? [NSIndexPath]

这是从服务器获取结果的 url

   example : category_id=1,9&city_id=2,4

   http://www.events/events/searchEventsByCategory?category_id=1,9&city_id=2,4

感谢您的帮助

【问题讨论】:

  • 您是否尝试过使用tableView.indexPathsForSelectedRows
  • 谢谢。请查看我编辑的问题
  • 你问的是如何构造url字符串?

标签: ios arrays swift uitableview dictionary


【解决方案1】:

假设你有一个 categoriesTableView、citiesTableView 并且你的数组被命名为 categoryArray 和 cityArray

//create string of selected categories
let list = categoriesTableView.indexPathsForSelectedRows() as? [NSIndexPath];
let categoryIds = "";
for (let indexPath in list) {
    if (categoryIds.length == 0) {
        categoryIds = categoryArray[indexPath.row]["Category_ID"])
        continue
    }
    categoryIds = "\(categoryIds),\(categoryArray[indexPath.row]["Category_ID"])"
}

//create string of selected cities
list = citiesTableView.indexPathsForSelectedRows() as? [NSIndexPath];
let citiesIds = "";
for (let indexPath in list) {
    if (citiesIds.length == 0) {
        citiesIds = cityArray[indexPath.row]["City_id"])
        continue
    }
    citiesIds = "\(citiesIds),\(cityArray[indexPath.row]["City_id"])"
}

你的网址会是这样的:

let url = "http://www.events/events/searchEventsByCategory?category_id=\(categoryIds)&city_id=\(citiesIds)"

【讨论】:

  • 告诉我到底是什么不工作?它创建哪个 URL?
【解决方案2】:

将 2 设为数组并将选定的索引目录添加到数组中

说选定的类别和选定的城市

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//add selected dictory in selectedArray

}

在选择之后通过添加for循环来制作字符串

【讨论】:

  • 谢谢。您能指出任何与此相同或相关的示例吗?
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 2020-03-27
  • 2021-03-22
  • 2021-09-01
  • 1970-01-01
相关资源
最近更新 更多