【问题标题】:UISearchBar and JSON DataUISearchBar 和 JSON 数据
【发布时间】:2018-02-19 04:37:42
【问题描述】:

这是我第一次使用 UISearchBar,结果让我很困惑。

我认为我最大的问题是不了解 JSON 是如何存储和显示的。

我的 JSON 数据存储为:

    [{
  "referralId" : "v-1519014616",
  "name" : "Empire State Building",
  "storeId" : "",
  "hereNow" : {
    "count" : 2,
    "summary" : "2 people are here",
    "groups" : [
      {
        "count" : 2,
        "type" : "others",
        "name" : "Other people here",
        "items" : [

        ]
      }
    ]
  },
  "stats" : {
    "tipCount" : 1105,
    "checkinsCount" : 185916,
    "usersCount" : 129661
  },
  "venueRatingBlacklisted" : true,
  "beenHere" : {
    "lastCheckinExpiredAt" : 0
  },
  "specials" : {
    "count" : 0,
    "items" : [

    ]
  },
  "venuePage" : {
    "id" : "64514349"
  },
  "verified" : true,
  "location" : {
    "state" : "NY",
    "neighborhood" : "Midtown Manhattan, New York, NY",
    "crossStreet" : "btwn 33rd & 34th St",
    "lat" : 40.748469532965927,
    "address" : "350 5th Ave",
    "cc" : "US",
    "city" : "New York",
    "postalCode" : "10118",
    "formattedAddress" : [
      "350 5th Ave (btwn 33rd & 34th St)",
      "New York, NY 10118"
    ],
    "lng" : -73.985513794430119,
    "distance" : 17,
    "country" : "United States"
  },
  "hasPerk" : false,
  "id" : "43695300f964a5208c291fe3",
  "categories" : [
    {
... etc
},

我将它存储在一个名为位置的数组中,我正在尝试使用搜索栏对其进行过滤。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let name = self.locations[0]["name"].string
        filteredLocations = locations.filter { names in
            return (name!.lowercased().contains(searchText.lowercased()))
        }

        tableView.reloadData()
    }

现在,很明显,name 只会搜索数组中的项目。我如何才能过滤每个位置的 name 键以正确过滤?

【问题讨论】:

  • 没有人知道 self.locations 是什么,或者如果它是一个存储字典对象的数组会是什么样子。
  • @ElTomato 存储为 ArrayValue - 这有帮助吗?

标签: json swift uisearchbar


【解决方案1】:

试试这个 ...不要先从位置数组中取名字...

 let filterArr = locations.filter {
        return (($0["name"] as! String).lowercased().contains(searchText.lowercased())))
    }

用这个获取搜索结果

【讨论】:

  • 这行得通。如果你不介意,我有几个问题。首先:为什么它让你调用 $0["name"] 而不是 locations["name"]?第二:我将其更改为 $0["name"].stringValue 这与明确将其称为字符串有什么不同吗?我非常感谢您在这里的帮助。 @pradeep
  • locations["name"].. 你不能像这样访问字典数组,这意味着没有索引值......第二个是 $0["name"].stringValue 你可以从这里读取你会知道为什么...stackoverflow.com/questions/32837053/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多