gpt4 book ai didi

ios - 使用循环到几个 subview (swift4)

转载 作者:行者123 更新时间:2023-11-28 23:34:25 24 4
gpt4 key购买 nike

我下面的代码声明变量,然后将它们添加到 View subview 中,同时声明约束。我想看看是否可以将这段代码写得更短。使用 view.addSubview(imageA) 和 imageA.translatesAutoresizingMaskIntoConstraints = false 我想看看是否有无论如何我可以添加所有变量,所以它像 imageA, text,textBackward.addSubview(theName)

var imageA = UIImageView()
var text = UILabel()
var theName = UILabel()
var textForward = UIButton()
var textBackward = UIButton()
var map = UIButton()
var settings = UIButton()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

view.addSubview(imageA)
view.addSubview(text)

view.addSubview(theName)
view.addSubview(textForward)
view.addSubview(textBackward)
view.addSubview(map)
view.addSubview(settings)

imageA.translatesAutoresizingMaskIntoConstraints = false
text.translatesAutoresizingMaskIntoConstraints = false
textBackward.translatesAutoresizingMaskIntoConstraints = false
settings.translatesAutoresizingMaskIntoConstraints = false
theName.translatesAutoresizingMaskIntoConstraints = false
map.translatesAutoresizingMaskIntoConstraints = false

textForward.translatesAutoresizingMaskIntoConstraints = false
}

最佳答案

对我来说,我喜欢将所有属性放入一个数组,并使用每个闭包来设置调用闭包内的相同函数。

    var imageA = UIImageView()
var text = UILabel()
var theName = UILabel()
var textForward = UIButton()
var textBackward = UIButton()
var map = UIButton()
var settings = UIButton()

lazy var collection = [imageA, text, theName, textForward, textBackward, map, settings]

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

collection.forEach { (view) in
self.view.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
}
}

如果有人使用 storyboard 和 outlet 也可以添加一个 outlet 集合并链接所有你想要的 View 。 outlet collection

关于ios - 使用循环到几个 subview (swift4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55486324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com