在创建新的ViewController实例时没有任何意义

时间:2016-04-09 15:47:24

标签: ios swift uiviewcontroller

我在其他ViewController中完成一些操作之后创建了新的ViewController(它是自定义AlertController),之后出现错误"在解包一个Optional值"时意外地发现了nil。这是代码:

    class CustomAlertController: UIViewController {
      @IBOutlet weak var titleLabel: UILabel!
      @IBOutlet weak var messageLabel: UILabel!
      @IBOutlet weak var okButton: UIButton!

internal func loadFromStoryboard() -> CustomAlertController! {
        let alertsStoryboard = UIStoryboard(name: "Alerts", bundle: NSBundle.mainBundle())
        let alertControllerStoryboardVC = alertsStoryboard.instantiateViewControllerWithIdentifier("CustomAlertController") as! CustomAlertController
        return alertControllerStoryboardVC
    }

class func showAlert(controller: UIViewController? = nil, title: String, message: String, okTitle: String, completion: ()->Void = {}) {
        let customAlertVC = CustomAlertController().loadFromStoryboard()
        customAlertVC.modalPresentationStyle = UIModalPresentationStyle.Custom

        let localTransitioningDelegate = AlertTransitioningDelegate()
        customAlertVC.transitioningDelegate = localTransitioningDelegate

        customAlertVC.titleLabel.text = title
        customAlertVC.messageLabel.text = message
        customAlertVC.okButton.titleLabel?.text = okTitle


        if controller != nil {
            controller?.modalPresentationStyle = .OverCurrentContext
            controller?.presentViewController(customAlertVC, animated: true, completion: nil)
        }
        else {
            print("something went wrong, friend")
        }
    }

在另一个ViewController中,我有:

CustomAlertController.showAlert(self, title: "Success!", message: "Operation done", okTitle: "OK")

问题是 titleLabel ,其他必须设置的属性为零。

任何帮助都会有用。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

IBOutlets是零,因为instantiateViewControllerWithIdentifier没有加载视图和子视图 - 这会在出现alertController时发生。只需将变量添加到CustomAlertController类:

var title = ""
var message = ""
var okButtonTitle = ""

并设置这些值而不是尝试访问IBOutlets:

customAlertVC.title = title
customAlertVC.message = message
customAlertVC.okButtonTitle = okTitle

然后覆盖viewDidLoad以使用以下值配置标签/按钮:

self.titleLabel.text = title
self.messageLabel.text = message
self.okButton.setTitle(okButtonTitle, forState: .Normal)

另请注意,您应使用.setTitle(, forState: .Normal)而不是直接设置标题标签。