如何在初始化 IBOutlet 时初始化变量?

How to initialize a variable when IBOutlet is initialized?

我碰巧在我的新 iOS Swift 应用程序中的一个 UIViewControllers 中编写了以下代码片段。

var starButtonsCount = starButtons.count
@IBOutlet var starButtons: [UIButton]!

然后直接旁边的starButtonsCount变量声明下面出现了红色的错误

Error: Cannot use instance member ‘starButtons’ within property initializer; property initializers run before ‘self’ is available.

所以我发现通过将starButtonCount变量声明为lazy我们可以解决这个错误(临时在iOS App开发过程中的漫长运行 ).

我很想知道解决这个问题的其他方法是什么?

有没有办法在 starButtons IBOutlets 初始化时触发 starButtonCount 的初始化?

另一种方式

var starButtonsCount:Int! 
@IBOutlet var starButtons: [UIButton]! { 
    didSet { 
         starButtonsCount = starButtons.count
    }
}

awakeFromNib 是在 .xib 中的每个对象都被反序列化并且所有出口的图形都已连接时调用的方法。文档说:

Declaration

func awakeFromNib()

Discussion

message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.The nib-loading infrastructure sends an awakeFromNib

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additional initialization they require. Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations. You may call the super implementation at any point during your own awakeFromNib method.

如:

class MyUIViewController : UIViewController {
    var starButtonsCount = 0
    @IBOutlet var starButtons: [UIButton]!
    override func awakeFromNib() {
        super.awakeFromNib()
        starButtonsCount = startButtons.count
    }
}

另请注意,starButtonsCount 无需成为存储变量:

var starButtonsCount: Int {
   return starButtons.count
}

在这种情况下,直接使用 starButtons.count 可能会更好,因为变量不会以任何方式改进代码。

在一般情况下,不需要存储派生状态,除非存储它可以提供一些性能提升(例如缓存计算)。

简单的解决方案是一个常数

let starButtonsCount = 8 // or whatever the number of buttons is

IBOutlets 在构建时连接,因此按钮数量在运行时不会改变。

您可以在 viewDidLoad 中添加断言行,以便在应用程序的未来版本中更改按钮数量时得到通知

assert(starButtons.count == starButtonsCount, "number of buttons has changed, adjust starButtonsCount")