Sonia Perez
Sonia Perez

Reputation: 1

Swift error "Only instance properties can be declared @IBOutlet"

I'm trying to make the buttons with rounded corners. So far this is what I have. I keep getting the "Only instance properties can be declared @IBOutlet" error.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


}
  
    @IBOutlet var Button: UIButton! {
        didSet {
            Button.backgroundColor = .clear
            Button.layer.cornerRadius = 5
            Button.layer.borderWidth = 0.8
            Button.layer.borderColor = UIColor.black.cgColor
    }
    
    }
    
    @IBOutlet weak var sampleButton: UIButton! {
        didSet {
            sampleButton.layer.cornerRadius = 5
            sampleButton.layer.borderWidth = 0.8
            
        }
    }

Upvotes: -3

Views: 717

Answers (1)

MANIAK_dobrii
MANIAK_dobrii

Reputation: 6032

Your Button and sampleButton are not instance variables because they are defined outside of any type scope:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


} // <---- end of ViewController class scope
  
    @IBOutlet var Button: UIButton! {
        didSet {
            Button.backgroundColor = .clear
            Button.layer.cornerRadius = 5
            Button.layer.borderWidth = 0.8
            Button.layer.borderColor = UIColor.black.cgColor
    }
    
    }
    
    @IBOutlet weak var sampleButton: UIButton! {
        didSet {
            sampleButton.layer.cornerRadius = 5
            sampleButton.layer.borderWidth = 0.8
            
        }
    }

So you're applying @IBOutlet attribute to a global variable, hence the error. I suspect it was not the intention, and Button with sampleButton should be instance variables of the ViewController class.

Move that closing bracket down to include Button and sampleButton in ViewController:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
  
    @IBOutlet var Button: UIButton! {
        didSet {
            Button.backgroundColor = .clear
            Button.layer.cornerRadius = 5
            Button.layer.borderWidth = 0.8
            Button.layer.borderColor = UIColor.black.cgColor
    }
    
    }
    
    @IBOutlet weak var sampleButton: UIButton! {
        didSet {
            sampleButton.layer.cornerRadius = 5
            sampleButton.layer.borderWidth = 0.8
            
        }
    }
} // <---- moved the bracket down

Upvotes: 1

Related Questions