使用循环访问多个子视图(swift4)

时间:2019-04-03 02:53:52

标签: ios loops for-loop swift4 var

我下面的代码声明了var,然后将它们添加到views子视图中,还声明了约束。我想看看是否仍然可以将这段代码写得更短。使用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
  }

2 个答案:

答案 0 :(得分:1)

对我来说,我喜欢将所有属性都放到Array中,并用于每个闭包以在闭包内设置调用相同的函数。

    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
        }
    }

如果有人使用情节提要和插座,还可以添加插座集合并链接所需的所有视图。 outlet collection

答案 1 :(得分:0)

您可以将所有子视图添加到数组中并像这样进行迭代

[imageA,text,theName,textForward,textBackward,map,settings].forEach({
            $0.translatesAutoresizingMaskIntoConstraints = false
            self.view.addSubview($0)
        })