我使用的类是 MessageView
( Swift Message Library) 的子类,继承自 UIView
。在里面,我有一个 UIButton
,我想通过它以编程方式呈现另一个 ViewController
。
下面是我的代码:
import Foundation
import SwiftMessages
import UIKit
class MyClass: MessageView {
var hideBanner: (() -> Void)?
@IBAction func helpButtonPressed(_ sender: UIButton) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
self.present(newViewController, animated: true, completion: nil)
@IBAction func tryAgainButtonPressed(_ sender: UIButton) {
hideBanner?()
}
open override func awakeFromNib() {
}
}
我试过这个,但它不起作用,因为 UIView
没有 present 方法。
最佳答案
首先使用这个获取顶级 ViewController
。然后你可以展示你的 viewController
。
if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
// topController now can use for present.
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
topController.present(newViewController, animated: true, completion: nil)
}
关于ios - 如何以编程方式从 UIVIew 呈现 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50209128/