简体   繁体   中英

Is there a way to use a loop to tag mulitple items (swift3)

This is the code I am trying to shorten. I would think there is a loop for it but I am not sure.

piker1.tag = 1
    piker2.tag = 2
    piker3.tag = 3
    piker4.tag = 4
    piker5.tag = 5
    piker6.tag = 6
    piker7.tag = 7
    piker8.tag = 8
    piker9.tag = 9
    piker10.tag = 10
    piker11.tag = 11
    piker12.tag = 12
    piker13.tag = 13
    piker14.tag = 14

You cannot generate variable names dynamically, since variable names need to be known at compile time, so you cannot do what you are trying to do.

If you put all buttons in an array, you can iterate through the array and assign the tags in a loop, but you still need to manually add the buttons to an array.

let pikers = [piker1, piker2,...piker14]
for i in 0..<pikers.count {
    pikers[i].tag = i
}

The most elegant way is to have an IBOutlet Collection instead of a simple IBOutlet for every picker. 在此处输入图片说明

Just drag and drop from the first picker as you would do with a simple outlet, but change the Connection to Outlet Collection. Then drag and drop the other pickers to the same outlet. You will get an array of pickers. Then iterate over them:

for (index, picker) in pickers.enumerated() {
    picker.tag = index + 1
}

Voala!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM