我目前正在尝试(以编程方式)构建一个包含 5 个按钮的界面,其中包含一个图像和一个标签。
我已经使用 UIStackView(持有 UIButton 和 UIlabel)为一个按钮成功完成了此操作。
我有两个关于这个论坛的问题......
- 可以构建一个 UIButton 来显示标题或图像,它可以同时拥有两者吗?
- 能否使用“for in”循环生成 5 个单独的按钮?即:一种重用代码的方法,而不是为 5 个按钮、5 个标签、5 个堆栈 View 键入代码。
我的工作 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
最佳答案
当然,UIButton 可以同时具有图像或/和文本。您可以使用:
button.setImage(image: UIImage?, for: UIControlState) button.setTitle(title: String?, for: UIControlState)
创建一个将返回 UIButton 的函数并执行类似的操作:
let button = generateButton() stackView.addArrangedSubview(button)
关于ios - Swift 3 - 以编程方式构建带有图像和标签的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45073768/