Jim W
Jim W

Reputation: 5016

Accessing or referring to UIImageView from the viewController

Total iOS/Swift newb here. I have a View (or UIImageView, don't think it matters) on my storyBoard and I need to refer to it in my viewController code. How do I do that?

Why? I'm trying to show the camera preview in a 'view' that is not full screen.

I'm using example code for the camera, which includes this code

func beginSession() {
var err : NSError? = nil
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))

if err != nil {
    println("error: \(err?.localizedDescription)")
}

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer)
previewLayer?.frame = self.view.layer.frame
captureSession.startRunning()
}

that seems to be saying, put the previewLayer in the (main) 'view' on my storyboard.

So I figured, and researched, that I could add a sub View (or a UIImageView) to my storyboard and make it the size I want, and then add previewLayer to it.

Eg. from another question on SO

... and then change the part at the bottom that says,

"previewLayer?.frame = self.view.layer.frame"

to your 200by200 View.layer.frame

Ok, so how do I get my 200x200 view, so I can access its frame (not even sure what layer and frame are at this point)?

I tried control drag the view, or UIImageView to the viewController from the storyboard, but it didn't work (did nothing).

Upvotes: 2

Views: 1854

Answers (2)

imike
imike

Reputation: 5656

I think my little tutorial and source code will help you!

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

And fill the code in ViewController.swift https://gist.github.com/MihaelIsaev/273e4e8ddaaf062d2155

Full source code here https://github.com/MihaelIsaev/SwiftCameraView

Upvotes: 3

Vlad
Vlad

Reputation: 7260

  1. Paste this line in your view controller's class:

    @IBOutlet weak var imageView: UIImageView!

  2. Open storyboard and select your view controller

  3. Open a connections inspector at the right side of Xcode window.

  4. Connect imageView outlet's circle with your image view.

    enter image description here

Upvotes: 6

Related Questions