5

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.

Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
smnk
  • 471
  • 1
  • 6
  • 25
  • 1
    You need to access a real instance of `ViewController` and not some generic instantiation – Ian Feb 04 '15 at 22:29
  • Can you give me some example Code on how to do this? – smnk Feb 04 '15 at 22:29
  • Why not just set the corner radius in your ViewController? – Ian Feb 04 '15 at 22:33
  • This is just some example Code I provided. I do have a lot more Buttons to take care of. I just don't want all that text in the same .swift file as the other methods if this makes any sense :D – smnk Feb 04 '15 at 22:34
  • 2
    if all the buttons are on the same UIViewController, just make an extension of `ViewController` and that removes the need to have it in the same file. – Ian Feb 04 '15 at 22:36

2 Answers2

4

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.

Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
Christian
  • 22,585
  • 9
  • 80
  • 106
  • I am going to try this! :) – smnk Feb 04 '15 at 22:37
  • It seems to work if I use class func set_cornerRadius(yourView:ViewController, radius CGFloat) { some code } and call it with set_cornerRadius(self, 10) – smnk Feb 04 '15 at 22:40
2

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.

Ian
  • 12,538
  • 5
  • 43
  • 62