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.
weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended.
IBOutlet is a keyword which is added to a variable declaration. It's an indicator. It does not affect the declaration in any way. However, when the Interface Builder sees it, it will allows a programmer to set this variable through the “outlet” mechanism inside Interface Builder.
Swift code is associated with graphical interface elements through the use of outlets and actions. An IB Outlet (short for Interface Builder outlet) is a graphical component that your code links to. An IB action is the reverse: It is a method in your code that a graphical component links to.
How do you declare an IBOutlet property in Swift? Declare an @IBOutlet property in the appropriate Swift file. Drag from the circle plus icon that appears in the gutter to the left of that property to the view on the storyboard that you would like to hook up.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With