-3

我正在尝试制作带有圆角的按钮。到目前为止,这就是我所拥有的。我不断收到“只能声明实例属性@IBOutlet”错误。

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
            
        }
    }
4

1 回答 1

1

您的ButtonandsampleButton不是实例变量,因为它们是在任何类型范围之外定义的:

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
            
        }
    }

因此,您将 @IBOutlet 属性应用于全局变量,因此会出现错误。我怀疑这不是故意的,Button应该sampleButtonViewController类的实例变量。

向下移动该右括号以包含Buttonand sampleButtonin 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
于 2022-01-11T22:06:57.403 回答