我的視圖控制器中有帶有文本欄位的 UIAlertController。當用戶輸入城市名稱時,當我得到這個城市的坐標時,這個資料必須傳輸到模型。但我不能將城市名稱從 View Controller 傳遞給 Model
我的 UIAlertController:
class MainScrenenViewController: UIViewController {
var delegate: ILocationGroup?
@objc func locationButtonTap() {
let alert = UIAlertController(title: "Add city", message: nil, preferredStyle: .alert)
let addButton = UIAlertAction(title: "Add", style: .default) { action in
self.delegate?.addLocation(alert.textFields?.first?.text ?? "No City")
}
alert.addAction(addButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(cancelButton)
alert.addTextField { textField in
textField.placeholder = "Your City"
}
present(alert, animated: true, completion: nil)
}
我的型號:
protocol ILocationGroup {
func addLocation(_ name: String)
}
class LocationGroup: ILocationGroup {
var mainScreenViewController: MainScrenenViewController?
func addLocation(_ name: String) {
mainScreenViewController?.delegate = self
let url = "https://geocode-maps.yandex.ru/1.x/?apikey=fd93783b-fe25-4428-8c3b-38b155941c8c&format=json&geocode=\(name)"
guard let url = URL(string: url) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
do {
let result = try JSONDecoder().decode(LocationData.self, from: data)
print(result.response.geoObjectCollection.metaDataProperty.geocoderResponseMetaData.boundedBy.envelope.lowerCorner)
}
catch {
print("failed to convert \(error)")
}
}
task.resume()
}
}
uj5u.com熱心網友回復:
我認為它應該是 var 委托:LocationGroup()
另外,我不會稱它為委托,因為注冊委托是 swift 中的關鍵字
https://manasaprema04.medium.com/different-ways-to-pass-data-between-viewcontrollers-views-8b7095e9b1bf
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394795.html
標籤:迅速 代码 uialert控制器
上一篇:更新到Swift5后AppDelegate.Swift編譯錯誤
下一篇:接受T&C后中斷購買不呼叫代表
