Search code examples
iosloopsfor-loopswift4var

use loop to several subviews (swift4)


My code below is declaring vars and then adding them to the views subview also declaring constraints. I want to see if there is anyway I can write this code shorter. With view.addSubview(imageA)and imageA.translatesAutoresizingMaskIntoConstraints = false I would like to see if there is anyway I can add all of the vars so its like 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
  }

Solution

  • You can add all subviews in an array and iterate like this

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