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

时间:2017-07-13 07:12:45

标签: ios swift3 uibutton uistackview

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

我使用UIStackView(持有UIButton和UIlabel)成功完成了一个按钮。

我对这个论坛有两个问题......

  1. 可以构建UIButton来显示标题或图像,它可以同时显示吗?
  2. 可以使用'for in'循环生成5个单独的按钮吗?即:一种重用代码的方法,而不是输入5个按钮,5个标签,5个堆栈视图的代码。
  3. 我正在使用的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 个答案:

答案 0 :(得分:2)

  1. 当然,UIButton可以同时拥有图像或/和文本。您可以使用:

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

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