user10764035
user10764035

Reputation:

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
  }

Upvotes: 0

Views: 59

Answers (2)

Leon
Leon

Reputation: 11

For me, I like to put all properties to an Array and use for each closure to set call the same function inside the closure.

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

If someone using storyboard and outlet also can add a outlet collection and link all the views you want. outlet collection

Upvotes: 1

RajeshKumar R
RajeshKumar R

Reputation: 15758

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

Upvotes: 0

Related Questions