【问题标题】:Swift 5: Stuck on the searchTextField. Trying to do a search of city, state, and countrySwift 5:卡在 searchTextField 上。试图搜索城市、州和国家
【发布时间】:2020-10-14 15:43:38
【问题描述】:

我卡住的部分是当我在搜索栏中输入城市名称、州名称和国家名称时,它不会更新城市标签、州标签或国家标签。

下面是 searchPressed 的代码:

extension AirQualityViewController: UITextFieldDelegate {
@IBAction func searchPressed(_ sender: UIButton) {
    print(searchTextField.text!)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    searchTextField.endEditing(true)
    print(searchTextField.text!)
    return true
}

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    if textField.text != "" {
        return true
    } else {
        textField.placeholder = "Type something"
        return false
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if let city = searchTextField.text, let state = searchTextField.text, let country = searchTextField.text {
        airQualityManager.fetchAirQuality(cityName: city, stateName: state, countryName: country)
    }
    searchTextField.text = ""
}

}

这就是我所说的获取空气质量的方式:

func fetchAirQuality(cityName: String, stateName: String, countryName: String) {
    let urlString = "\(cityURL)city=\(cityName)&state=\(stateName)&country=\(countryName)&key=\(apiKey)"
    performRequest(urlString: urlString)
    
}

func fetchAirQuality(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
    let urlString = "\(nearCityURL)lat=\(latitude)&lon=\(longitude)&key=\(apiKey)"
    performRequest(urlString: urlString)
}

在 func textFieldDidEndEditing 中,是否有另一种方法可以分别获取城市名称、州名称和国家名称的文本字段?

【问题讨论】:

  • 您不是只使用一个文本字段吗?您想要 3 个单独的文本字段,还是只需要 1 个输入 3 个术语的地方?
  • @aheze 我们输入 3 个术语的地方只有 1 个。我试图弄清楚如何用像这样的字符来分隔“,”

标签: json swift api url textfield


【解决方案1】:

这将为您提供每个元素的数组,您可以通过索引直接访问它们。

let array = str.components(separatedBy: ",")

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 2011-01-14
    • 1970-01-01
    • 2014-09-08
    • 2014-09-08
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多