您如何以编程方式添加 UI / 视图控制器?

How do you programmatically add UI / view controllers?

我试图在点击 UIView 时加载 ViewController,但我一直收到错误

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Storyboard () doesn't contain a view controller with identifier 'CameraVC3''

我认为我的故事板中没有正确添加 ViewController,所以我尝试以编程方式进行,但仍然无法识别。

ViewController

class ViewController: UIViewController, UIScrollViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate{

    let rect1 = CGRectMake(100, 60, 40, 60)
    let captureButton2 = UIView(frame: rect1)
    captureButton2.backgroundColor = UIColor.blueColor()
    scrollView.addSubview(captureButton2)
    captureButton2.addGestureRecognizer(UITapGestureRecognizer(target: self,
       action: Selector("didTapImageView:")))

    func didTapImageView(tap: UITapGestureRecognizer){

         let captureDetails = storyboard!.instantiateViewControllerWithIdentifier("CameraVC3")! as! CameraVC3
         presentViewController(captureDetails, animated: true, completion: nil)

}

相机ViewController

class CameraVC3: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{

    override func viewWillAppear(animated: Bool) {
    println("camera vc3 view will appear")
    super.viewWillAppear(animated)

    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "capture:"))
}

func capture() {
     if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
    var imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
    imagePicker.mediaTypes = [kUTTypeImage]
    imagePicker.allowsEditing = false
    self.presentViewController(imagePicker, animated: true, completion: nil)
}

为了使用 UIStoryboardinstantiateViewControllerWithIdentifier 方法,您必须设置视图控制器的标识符以匹配您作为标识符传递的字符串。

故事板上的视图控制器可以通过身份检查器设置其标识符(与您为视图控制器设置自定义 class 的位置相同):

在 "Storyboard ID" 的框中,只需填写一个字符串作为此视图控制器的标识。在这种情况下,将 CameraVC3 放入该框。

用线:

let captureDetails = storyboard!.instantiateViewControllerWithIdentifier("CameraVC3")! as! CameraVC3

您需要在故事板中为您的 ViewController 提供一个标识符名称 "CameraVC3"。您可以在身份检查器中的 Storyboard ID.

字段中进行设置