我试图在视图控制器上展示一个以编程方式制作的视图控制器,在这里我不知道如何制作这样的组合视图控制器的ID。
从下面的代码中可以看到,我有一个基本的视图控制器“ ViewController”,如果我单击一个按钮(didTapButton),我希望以编程方式显示视图控制器(SecondViewController)。 尽管我无法设置第二个视图控制器的名称,但我什至无法执行代码-InstantiateViewController(withIdentifier:“ SecondController”)。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func didTapButton(_ sender: Any) {
let controller = storyboard!.instantiateViewController(withIdentifier: "SecondController")
present(controller, animated: true)
}
}
......
class SecondViewController: UIViewController {
private var customTransitioningDelegate = TransitioningDelegate()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "SecondController", bundle: nibBundleOrNil)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
}
如何设置第二个视图控制器的ID?如果不是应该执行的操作,我还能尝试什么?
答案 0 :(得分:1)
以编程方式创建的vc,您不需要任何标识符
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
}
}
使用方式
@IBAction func didTapButton(_ sender: Any) {
let vc = SecondViewController()
present(vc, animated: true)
}
编辑:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
let vc2 = SecondViewController()
vc2.providesPresentationContextTransitionStyle = true
vc2.definesPresentationContext = true
vc2.modalPresentationStyle = .overCurrentContext
self.present(vc2, animated: true)
}
}
}
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let v = UIView()
v.backgroundColor = .red
view.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
v.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
v.widthAnchor.constraint(equalToConstant:200),
v.heightAnchor.constraint(equalToConstant:200)
])
}
}
答案 1 :(得分:1)
instantiateViewController
使您可以实例化给定情节提要中定义的内容。因此,要么通过xcode在情节提要中为其命名,要么必须做其他事情。例如,通过代码实例化对象let c=SecondViewController()
(具有适当的参数)。您正在尝试混合使用各种实例化对象。