每次视图控制器启动时显示 UIAlertController

Show UIAlertController every time view controller launches

目前,UIAlertController 在用户点击 HeaderButton 时出现。我试图让 UIAlertController 在每次视图控制器最初启动时自动出现。有什么建议吗?

// MARK: - RestaurantListTableViewHeaderDelegate
extension RestaurantListViewController: RestaurantListTableViewHeaderDelegate {
  func didTapHeaderButton(_ headerView: RestaurantListTableViewHeader) {
    let locationPicker = UIAlertController(title: "Select location", message: nil, preferredStyle: .actionSheet)
    for location in RestaurantListViewController.locations {
      locationPicker.addAction(UIAlertAction(title: location, style: .default) { [weak self] action in
        guard let `self` = self else { return }
        self.currentLocation = action.title
        self.tableView.reloadData()
      })
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    locationPicker.addAction(cancelAction)
    present(locationPicker, animated: true)
  }
}

这不是一个优雅的解决方案,但它会起作用:

var alertAlreadyShown = false

override func viewWillAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  if !alertAlreadyShown {
      alertAlreadyShown = true
      /* Code for showing alert */
  }
}

我保留了点击 Header Button 时的扩展名,并将以下内容添加到 viewDidLoad:

// Code for showing alert
let locationPicker = UIAlertController(title: "Select location", message: nil, preferredStyle: .actionSheet)
for location in RestaurantListViewController.locations {
  locationPicker.addAction(UIAlertAction(title: location, style: .default) { [weak self] action in
    guard let `self` = self else { return }
    self.currentLocation = action.title
    self.tableView.reloadData()
  })
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
locationPicker.addAction(cancelAction)
present(locationPicker, animated: true)