gpt4 book ai didi

ios - 如何在 Swift 中封装 UIViewController(如 UIAlertController)?

转载 作者:行者123 更新时间:2023-11-28 16:05:58 29 4
gpt4 key购买 nike

我的 Storyboard 中有一个 ViewController,它的工作方式类似于警报(带有标题、消息和两个按钮)。

我想封装它以便能够在我的代码中的任何地方使用它,就像这样:

let alert = CustomAlertViewController(title: "Test", message: "message de test.", view: self.view, delegate: self)
self.present(alert, animated: false, completion: nil)

我的问题是 IBOutlets 没有初始化...

我的 CustomAlertViewController:

public protocol CustomAlertProtocol {
func alertAccepted()
}

class CustomAlertViewController: UIViewController {

var delegate :CustomAlertProtocol? = nil
var parentView :UIView?
var blurScreenshot :SABlurImageView?

var alertTitle :String? = nil
var alertMessage :String? = nil

@IBOutlet weak var oAlertView: UIView!
@IBOutlet weak var oAlertTitle: UILabel!
@IBOutlet weak var oAlertMessage: UILabel!


//MARK: - Main

public convenience init(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) {
self.init()
self.alertTitle = title
self.alertMessage = message
self.delegate = delegate
self.parentView = view
}

override func viewDidLoad() {
oAlertTitle.text = self.alertTitle
oAlertMessage.text = self.alertMessage
}

@IBAction func onAcceptButtonPressed(_ sender: AnyObject) {
delegate?.alertAccepted()
}
}

最佳答案

将 View Controller 的 Custom Class 属性设置为 CustomAlertViewController
Storyboard ID 到你想要的任何东西 - 例如InterfaceBuilder 的身份检查器中的 CustomAlertViewControllerIdentifier

然后像下面这样实例化它:

let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

guard let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as? CustomAlertViewController else {
return
}

编辑:

然后您可以将该代码放入类函数中,例如:

extension CustomAlertViewController {
class func instantiateFromStoryboard(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) -> CustomAlertViewController {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as! CustomAlertViewController

vc.title = title
vc.message = message
vc.view = view
vc.delegate = delegate

return vc
}
}

然后像这样使用:

let myCustomAlertViewController = CustomAlertViewController.instantiateFromStoryboard(title: "bla", ...)

关于ios - 如何在 Swift 中封装 UIViewController(如 UIAlertController)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259623/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com