arrays - declare var as a group in swift
问题描述
I want to declare a group of the same objects like this.
var dave, paul, sam = UILabel()
I have tried various things. But I have not been able to do anything different to declare vars except the standard.
var dave = UILabel()
var paul = UILabel()
var sam = UILabel()
I would think there has to be someway to put this in a array to speed up the process.
解决方案
Rather than using named variables, you can just create an array of labels:
let labels = (0..<3).map { _ in UILabel() }
Or you might as well configure them as you create them:
let labels = (0..<3).map { _ -> UILabel in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
You can do whatever other configuration of them you want in that closure.
Now you can use them. For example, you might add them to your view which already has a vertical stack view (which gets you out of the business of manually adding constraints for each label), like so:
func viewDidLoad() {
super.viewDidLoad()
for label in labels {
stackView.addArrangedSubview(label)
}
}
And if you wanted to set the text for these labels:
labels[0].text = "Dave"
labels[1].text = "Paul"
labels[2].text = "Sam"
Here is a playground that illustrates the above:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
return stackView
}()
let labels = (0..<3).map { _ -> UILabel in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
override func viewDidLoad() {
super.viewDidLoad()
addStackView()
addLabels()
updateLabels()
}
}
private extension ViewController {
func addStackView() {
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
func addLabels() {
for label in labels {
stackView.addArrangedSubview(label)
}
}
func updateLabels() {
labels[0].text = "Dave"
labels[1].text = "Paul"
labels[2].text = "Sam"
}
}
PlaygroundPage.current.liveView = ViewController()
Now, if this was a proper app rather than a playground, I’d probably just add the stack view in IB, with an @IBOutlet
, rather than doing it programmatically, but I just wanted to illustrate the idea.
推荐阅读
- javascript - 选择新国家时删除突出显示的国家 geoJSON
- html - 在自动换行期间防止跨度之间的单词狭缝被拆分
- node.js - Express.js 如何在数据库调用后从数组中获取数据?
- mysql - 插入、删除、更新锁mysqld服务
- python - 我如何知道满足纸浆目标值的所有变量的所有组合?
- python-3.x - 将附加参数传递给只需要 1 的回调对象
- rust - 为什么在这种情况下发送需要同步?
- wordpress - WordPress 代码适用于 function.php,但不能作为独立插件
- snakemake - 从 yaml 文件构建蛇形环境的最佳方法
- android - 升级到 Kotlin 1.5.20 时出现谷歌地图问题