Swift:管理 UI 元素(例如 UI 按钮)的最佳方式?

Swift: Best way to manage UI elements, such as UIButtons?

我是 Swift 的新手。

我正在尝试为我经常使用的所有元素制作模板文件,例如按钮和标签。

你能告诉我最好的管理模板的方法吗?包括颜色、圆角半径在内的外观?

除了使用 Class 个文件,我无法弄清楚。

谢谢!

您可以这样创建 class:


class CustomButton: UIButton {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.layer.cornerRadius = 20
    }

}

并使用它:

您有 2 种方法可以做到。

1 - 创建您自己的 class

final class PrimaryButton: UIButton {

   override func awakeFromNib() {
       super.awakeFromNib()
       backgroundColor = UIColor.red
       setTitleColor(UIColor.black, for: .normal)
   }
}

2 - 创建要配置的扩展

extension UIButton {
    func style() {
        backgroundColor = R.color.primary()
        setTitleColor(R.color.black(), for: .normal)
    }
}

并在viewDidLoad中调用这个函数

首选第一种款式

就个人而言,我喜欢使用 same-named class 创建一个名为“Styling”的新文件。 然后,在其中,我创建了静态函数来接受您要编辑的参数(例如,按钮)。

class Styling {
   static func styleButton(_ button: UIButton) {
      button.layer.cornerRadius = 25.0
   }
}

然后我只需输入 vc:

来调用它
Styling.styleButton(myButton)

除了上述答案之外,对我有用的方法是将一系列按钮放在 UIButton 数组中。这使得在开发应用程序或适应各种屏幕时重新排列它们变得非常简单。

下面是 12 个按钮组成彩旗的简化示例:

var flagButton: [UIButton] = []
for i in 0...11 {
flagButton.append(UIButton())
flagButton[i].frame = CGRect(x: x, y: y, width: width, height: height)
self.view.addSubview(flagButton[i])
}