【问题标题】:UITableView data changes by typing the city name in FirstViewControllerUITableView 数据通过在 FirstViewController 中输入城市名称进行更改
【发布时间】:2017-09-17 00:02:40
【问题描述】:

我使用 Swift 3 我的第一个 ViewController 中有一个 textfield,当我输入城市名称时,我希望它在 tableView 中打开该城市的药店

示例:当我在 textField 中输入 New York 并按 Enter 时,它将转到 TableViewController 并给出纽约的药店列表:


纽约药房 1

纽约药房 2

纽约药房 3


当我返回并在 textField 中输入 California 并按 Enter 时,它将转到相同的 TableViewController 并给出加利福尼亚的药房列表:

加州药房 1

加州药房 2

加州药房 3


我用两个不同的 TableViewControllers 做到了,但我想在一个 TableViewController

中做到这一点

我不知道怎么做,需要帮助

【问题讨论】:

  • 您的药房列表/数据存储在哪里?我不明白你为什么需要多个数据源,只是过滤你的数据。有很多方法可以解决这个问题
  • 我刚刚为药房制作了两个数组,我不知道该怎么做我试图传递数据,但我的一位朋友无法告诉我,这可能是两个数据源的原因我说两个数据源。

标签: ios swift uitableview swift3 datasource


【解决方案1】:

如上所述,有多种方法可以做到这一点,我在下面提供的示例显示了位于不同位置的单个药房对象数组(来自结构)。然后有一个计算属性,它是一个由文本字段的内容过滤的列表。

struct Pharmacy {
   name: String
   location: String
}

let pharmacies: [Pharmacy] = [
   Pharmacy(name: "California Pharmacy 1", location: "California"),
   Pharmacy(name: "California Pharmacy 2", location: "California"),
   Pharmacy(name: "California Pharmacy 3", location: "California"),
   Pharmacy(name: "New York Pharmacy 1", location: "New York"),
   Pharmacy(name: "New York Pharmacy 2", location: "New York"),
   Pharmacy(name: "New York Pharmacy 3", location: "New York")
]

var filteredPharmacies: [Pharmacy] { get {
   return self.pharmacies.filter({ $0.location == self.locationTextField.text })
}}

请注意,上面当前编码的此选项仍需要进一步工作,如果文本字段不包含位置,则不会有结果,您可以通过更改过滤器来解决此问题,可能像这样...

var filteredPharmacies: [Pharmacy] { get {
   return self.locationTextField.isEmpty || self.pharmacies.filter({ $0.location == self.locationTextField.text })
}}

需要注意的主要事项是,您可以拥有一个单一的来源列表,并根据您可能拥有的任何过滤器对其进行过滤,并将过滤后的数据用作您的 tableView 数据源。

【讨论】:

    【解决方案2】:

    最后我发现了该怎么做,我就是这样做的:

    @IBAction func GoPressed(_ sender: Any) {
                if textField.text == "New York" || textField.text == "new york" {
                    let arrayForNewYork = ["New York Pharmacy 1","New York Pharmacy 2","New York Pharmacy 3"]
                    performSegue(withIdentifier: "Go", sender: arrayForNewYork)
                }else if textField.text == "California" || textField.text == "california" {
                    let arrayForCalifornia = ["California Pharmacy 1","California Pharmacy 2","California Pharmacy 3"]
                    performSegue(withIdentifier: "Go", sender: arrayForCalifornia)
                }
    

    感谢所有试图帮助我的人:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2020-06-22
      • 2012-03-07
      相关资源
      最近更新 更多