simnik
simnik

Reputation: 483

Accessing IBOutlet from another class

I am calling a class function from my ViewController class like this:

Buttons.set_cornerRadius(10)

I have another .swift file where I have the function declared:

class Buttons {

      class func set_cornerRadius(radius: CGFloat) {
          ViewController().someButton.layer.cornerRadius = radius
      }
}

When I'm trying to run this it throws the error: "Unexpectedly found nil while unwrapping an optional Value".

I checked the Storyboard-IBOutlet connections already. Everything is connected right.
If I call the method in the same class like this, everything works:

class ViewController: UIViewController {

    @IBOutlet weak var someButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        set_cornerRadius(10)
    }

    func set_cornerRadius(radius: CGFloat) {
        someButton.layer.cornerRadius = radius
    }
}

How can I fix this? What am I doing wrong/not understanding right?

Thanks in advance.

Upvotes: 5

Views: 2863

Answers (2)

Christian
Christian

Reputation: 22343

You access a generic ViewController, but need to use an existing UIView. Do something like this:

class Test: UIViewController {

    class func set_cornerRadius(yourView: UIView, radius: CGFloat) {
        yourView.layer.cornerRadius = radius
    }
}

That way, you pass the UIView you want to set the corner-radius.

Upvotes: 4

Ian
Ian

Reputation: 12768

You extend your ViewController class like so:

extension ViewController {
    func set_cornerRadius(radius: CGFloat) {
         someButton.layer.cornerRadius = radius
    }
}

Now you can call this method in your original ViewController file using: set_cornerRadius(someValue) in your viewDidLoad or wherever you want. You can put this extension in a different file.

Upvotes: 2

Related Questions