Swift 3 - 以编程方式构建带有图像和标签的按钮

Swift 3 - Programmatically build a button with an image and label

我目前正在尝试(以编程方式)构建一个包含 5 个按钮的界面,其中包含一个图像和一个标签。

我已经使用 UIStackView(持有 UIButton 和 UIlabel)为一个按钮成功完成了此操作。

我有两个关于这个论坛的问题…

  1. 可以构建一个 UIButton 来显示标题或图像,它可以同时拥有两者吗?
  2. 可以使用“for in”循环生成 5 个单独的按钮吗?即:一种 re-use 编码而不是为 5 个按钮、5 个标签、5 个堆栈视图键入代码的方法。

我的工作 UIStackView 按钮代码如下:

    // Button
    let btnSettings = UIButton()
//  btnSettings.setTitle("Settings", for: .normal)
    btnSettings.setImage(#imageLiteral(resourceName: "star-in-circle"), for: .normal)
    btnSettings.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
    btnSettings.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
    btnSettings.contentMode = .scaleAspectFit
    btnSettings.addTarget(self, action: #selector(openSettings), for: .touchUpInside)
    btnSettings.translatesAutoresizingMaskIntoConstraints = false

    // Text Label
    let textLabel = UILabel()
    textLabel.backgroundColor = UIColor.clear
    textLabel.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
    textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
    textLabel.font = UIFont.boldSystemFont(ofSize: 18)
    textLabel.text = "Settings"
    textLabel.textAlignment = .center

    // Stack View
    let stackView = UIStackView()
    stackView.axis = UILayoutConstraintAxis.vertical
    stackView.distribution = UIStackViewDistribution.equalSpacing
    stackView.alignment = UIStackViewAlignment.center
    stackView.spacing = 1.0

    stackView.addArrangedSubview(btnSettings)
    stackView.addArrangedSubview(textLabel)
    stackView.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(stackView)

    // Constraints
    stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

更新/解决问题 1

我需要使用 button.setBackgroundImage() 才能使按钮标题与图像一起显示。

btnSettings.setBackgroundImage(#imageLiteral(resourceName: "star-in-circle"), for: .normal)
btnSettings.setTitle("Button Title", for: .normal)
btnSettings.backgroundColor = UIColor.white
  1. 当然,UIButton 可以同时具有图像 or/and 文本。您可以使用:

    button.setImage(image: UIImage?, for: UIControlState)
    button.setTitle(title: String?, for: UIControlState)
    
  2. 创建一个 return UIButton 的函数并执行类似的操作:

    let button = generateButton()
    stackView.addArrangedSubview(button)