如何从委托方法初始化UIAlertController?

时间:2019-01-20 10:22:58

标签: ios swift uialertcontroller

我的代码很基本。我有2个ViewController。在名为“ FirstScreen”的第一个viewController上,有一个按钮,该按钮通过模式搜索将我带到第二个屏幕,在该屏幕上也有一个按钮。 “ SecondScreen”具有一种使用“ FirstScreen”所遵循的方法的协议。因此,基本上,我试图从该方法中调用UIAlertController,同时按下“ SecondScreen”的按钮。结果我得到了:

  

“警告:尝试显示.....在...上,其视图不在窗口中   等级!

我知道我可以将导航控制器嵌入到情节提要中,并且警报会起作用,但事实并非如此。我也想这样打电话给Alert,因为有必要知道CLAuthorizationStatus

  

所以也许有任何方法可以直接从   “第二屏幕”?

import UIKit
import CoreLocation

class FirstScreen: UIViewController {

    @IBAction func firstTapped(_ sender: UIButton) {
        let selectionVC = storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondScreen
        present(selectionVC, animated: true, completion: nil)
        selectionVC.delegate = self
    }
}

extension FirstScreen: LocationPermissionDelegate {

    func checkLocationStatus() {

        let status = CLLocationManager.authorizationStatus()
        if status == CLAuthorizationStatus.notDetermined {

            let alert = UIAlertController(title: "Just a message", message: "HEYYY!", preferredStyle: .alert)
            let action = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
            alert.addAction(action)
            present(alert, animated: true)
        }
    }
}

import Foundation
import UIKit

protocol LocationPermissionDelegate {
    func checkLocationStatus()
}

class SecondScreen: UIViewController {

    var delegate: LocationPermissionDelegate?

    @IBAction func secondTapped(_ sender: UIButton) {

        delegate?.checkLocationStatus()  
    }
}

1 个答案:

答案 0 :(得分:0)

firstvc当前正在显示

present(selectionVC, animated: true, completion: nil)

所以您不能在此处显示警报

present(alert, animated: true)

移动此

func checkLocationStatus() {

    let status = CLLocationManager.authorizationStatus()
    if status == CLAuthorizationStatus.notDetermined {

        let alert = UIAlertController(title: "Just a message", message: "HEYYY!", preferredStyle: .alert)
        let action = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
        alert.addAction(action)
        present(alert, animated: true)
    }
}

转到第二个vc,并在那里进行演示