如何在 swift 中为多个按钮创建一个 iboutlet

how to create one iboutlet for multiple buttons in swift

到目前为止,我只能为每个按钮创建一个 iboutlet。我想要实现的是为许多按钮创建一个 iboutlet,这样我就可以编写一次代码来在这些按钮周围创建相同的边框宽度、颜色和半径。这可能吗?

import UIKit
           
            class GameScreenViewController: UIViewController {
                @IBOutlet weak var answerTextLabel: UILabel!
                @IBOutlet weak var scoreLabel: UILabel!
                @IBOutlet weak var questionLabel: UILabel!
                @IBOutlet weak var numberBtn: UIButton! //this iboutlet is what i would like to be able to connect to multiple number buttons in my app.
    }

你可以使用 IBoutlet Collection !

声明为IBoutlet Collection后,您可以连接多个相同类型的对象。

如果你想运行相同的代码,你可以使用for语句。

for item in myButton {
     item.layer.cornerRadius = 3
 }

上面推荐的方案确实是正确的。有一个用于连接 IBOutlets 集合的选项。但是你需要确保它连接到集合的所有 IBOutlet 都是同一类型。例如仅 UIButtons 的集合。

您使用新引用插座集合而不是新引用插座进行连接