【发布时间】:2017-12-17 19:57:05
【问题描述】:
我目前正在尝试(以编程方式)构建一个带有 5 个 x 按钮的界面,其中包含一个图像和一个标签。
我已经使用 UIStackView(持有 UIButton 和 UIlabel)为 ONE 按钮成功完成了此操作。
我对这个论坛有两个问题......
- 可以构建一个 UIButton 来显示标题或图像,可以两者兼得吗?
- 可以使用“for in”循环生成 5 个单独的按钮吗?即:一种重用代码的方法,而不是为 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
【问题讨论】:
-
第一个问题的答案是 UIButton 可以同时具有 Title 和 Label 和 Second Answer 是的,您可以在 Loop 的帮助下制作按钮,但是对于操作,您必须为每个 UIButton 提供标签。
-
@GurinderBatth 感谢您的回答。有什么有用的建议吗?我尝试将 button.setTitle() 和 button.setImage() 添加到我的代码中,但它只显示图像,而不显示图像和标题。
标签: ios swift3 uibutton uistackview