K Y
K Y

Reputation: 47

Use func from different view controller swift

I uses storyboard to build the layout. I am trying to access func in firstViewController from secondViewController but when I use the following code to access it I will always get "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" no matter what function or outlet I have tried to access I always get the same error. Did I miss anything or am I doing it wrongly?

done is located in secondViewController

func done(){
    let vc =  firstViewController()
    vc.drawCircle(locationX: 0, locationY: 0)
}

drawCircle is located in firstViewController

func drawCircle(locationX:CGFloat, locationY: CGFloat) {
    let path = UIBezierPath(roundedRect: CGRect(x: locationX, y: locationY, width: radius, height: radius), cornerRadius: 50).cgPath
    combinePath.addPath(path)
    layer.path = combinePath

    if thickness>0{
        layer.strokeColor = UIColor(red: rColor, green: gColor, blue: bColor, alpha: 1).cgColor
        layer.fillColor = UIColor.clear.cgColor

        layer.lineWidth = thickness
    }
    imageView.layer.addSublayer(layer)

}

Upvotes: 0

Views: 75

Answers (3)

Faisal Memon
Faisal Memon

Reputation: 3454

The problem is due to the reference to imageView in function drawCircle because it means that in order for it to run, the firstViewController must be fully initialised and on-screen for the imageView to be "hooked up" to the User Interface.

Are both the firstViewController and secondViewController supposed to be on-screen at the same time?

To solve your problem you should drag two Container Views into your storyboard. The Custom Class (in the identity inspector) for each Container View should be firstViewController and secondViewController respectively.

Then when you are on-screen, both controllers will be initialised, and imageView will be hooked up properly (the Implicitly Unwrapped Optional will be non-nil). This means you will then be able to safely call the drawCircle method.

Upvotes: 0

Mahmut Acar
Mahmut Acar

Reputation: 743

If you are using storyboards, give an identifier to view controller and use this:

if let firstVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "firstViewController") as? firstViewController {
    firstVC.drawCircle(locationX: 0, locationY: 0)
}

Upvotes: 1

Huy Nguyễn
Huy Nguyễn

Reputation: 72

Default constructor does not create UI component from storyboard (IBOutlet, IBAction,..)

Upvotes: 1

Related Questions