我在其他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 ,其他必须设置的属性为零。
任何帮助都会有用。 提前谢谢!
答案 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)
而不是直接设置标题标签。