且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以更改Swift应用程序中所有按钮的属性吗?

更新时间:2023-11-20 21:29:52

以下是简化操作的基本步骤,在这种情况下,必须为每个viewController重复这一步骤。

Here are the basic steps which will simplify things, in your case this would have to be repeated for each viewController.


  1. 为所有按钮创建一个插座:

  1. Create one outlet for all your buttons:

@IBOutlet var myButtons: [UIButton]!


  • 使用视图上的每个按钮连接(拖动)此插座。单击界面中的每个按钮,并在连接检查器中找到引用插座集合(圆圈中带箭头的最后一个按钮)。请注意,它们都应该链接到 myButtons

  • Connect (drag) this outlet with each of the buttons on the view. Click on each of the buttons in your interface and checkout "Referencing Outlet Collections" found on in the connections inspector (the last button with the arrow in the circle). Notice that they should all by linked to myButtons.

    在for循环中设置按钮的样式: / p>

    Style your buttons in a for loop:

    for button in self.myButtons {
        button.backgroundColor = UIColor.clearColor()
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.greenColor().CGColor
    }
    


  • 要使这项工作适用于整个应用程序,您可以选择一些方法进行调查。您可以使用常量,因此至少在您希望更改样式时,您只需要修改一个文件: Objective-C中的常量 Swift中的全局常量文件

    To make this work application wide, you have a few options to investigate. You could use constants so at least when you wish to change the style, you only have to modify one file: Constants in Objective-C, Global constants file in Swift.

    或者那里有几种方法可以公开一个功能。我将尝试获取一些示例代码,但是一个名为 buttonStyle 的类对于每个viewController都很重要,并且在for循环中调用: [buttonStyle styleButton:键] styleButton 函数会设置样式(我没有为此测试任何内容)。

    Alternatively there are several ways to make a function public. I will try and get some example code, but a class called buttonStyle could be important into each viewController and called in the for loop: [buttonStyle styleButton:button]. The styleButton function would set the style (I haven't tested anything out for this).

    查看此答案通过@zisoft:如何使用Swift循环UIViewController的Outlets ,这是一个更详细的日志!

    Checkout this answer by @zisoft: How to loop through Outlets of a UIViewController with Swift, it is a log more detailed!.