我可以更改Swift应用程序中所有按钮的属性吗? [英] Can I change the properties of all the buttons in my Swift app?

查看:117
本文介绍了我可以更改Swift应用程序中所有按钮的属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swift应用程序可以浏览许多视图控制器,所有视图控制器都具有相似的外观。我没有创建IBOutlet属性的每个视图控制器中都有按钮(它们都只是通过Interface Builder触发segues)。

I have a Swift app that navigates through many view controllers, all with similar appearances. There are buttons in every view controller for which I have NOT created IBOutlet properties (they all just trigger segues via Interface Builder).

是否有一种简单的方法来更改背景应用程序中所有按钮的颜色或文本颜色,不更改IB中的每个按钮,或为每个按钮创建IBOutlet?

Is there an easy way to change the background color or text color of all the buttons in the app, without changing it for every button in IB, or creating an IBOutlet for each button?

推荐答案

以下是简化操作的基本步骤,在这种情况下,必须为每个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!.

    这篇关于我可以更改Swift应用程序中所有按钮的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆