有效地修改多个UIButton

时间:2017-02-18 21:23:04

标签: swift uibutton

我的视图中有3个按钮,我正在尝试添加阴影。这是我的代码:

@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()

    button1.layer.shadowColor = UIColor.black.cgColor
    button1.layer.shadowOpacity = 1
    button1.layer.shadowOffset = CGSize(width: 5, height: 5)
    button1.layer.shadowRadius = 0
    button2.layer.shadowColor = UIColor.black.cgColor
    button2.layer.shadowOpacity = 1
    button2.layer.shadowOffset = CGSize(width: 5, height: 5)
    button2.layer.shadowRadius = 0
    button3.layer.shadowColor = UIColor.black.cgColor
    button3.layer.shadowOpacity = 1
    button3.layer.shadowOffset = CGSize(width: 5, height: 5)
    button3.layer.shadowRadius = 0 
}

是否有更有效的方法对多个按钮执行此类操作,而不是仅为每个按钮重复相同的代码?

1 个答案:

答案 0 :(得分:1)

将您的按钮添加到Interface Builder

中的插座集合
@IBOutlet var buttonsWithShadow: [UIButton]!

现在您可以迭代集合,并以相同的方式配置所有按钮:

for button in buttonsWithShadow {
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOpacity = 1
    button.layer.shadowOffset = CGSize(width: 5, height: 5)
    button.layer.shadowRadius = 0
}