Setting isHidden to false on x amount of elements

2019-08-19 22:51发布

问题:

I am trying to unhide n number of elements depending on the users input into a text field.

So the user enters a number between 1 - 5 in the text field then clicks submit which calls createSplit. As you can see, it unhides a view and then I want it to loop x (x being the number the user inputs) amount of times to unhide day(i)View textfield

    @IBAction func createSplit(_ sender: Any)
{
    noOfExerciseView.isHidden = false
    let noOfDays: Int = Int(numberOfDays.text!)!
    for i in 1...noOfDays
    {
        day\(i)View.isHidden = false
    }
}

I have a working solution but it's not the most efficient so I hope someone can help doing this an efficient way.

    @IBAction func createSplit(_ sender: Any)
{
    noOfExerciseView.isHidden = false
    let noOfDays: Int = Int(numberOfDays.text!)!
    for i in 1...noOfDays
    {
        if (i==1)
        {
            day1View.isHidden = false
        } else if (i==2)
        {
            day2View.isHidden = false
        } else if (i==3)
        {
            day3View.isHidden = false
        } else if (i==4)
        {
            day4View.isHidden = false
        } else if (i==5)
        {
            day5View.isHidden = false
        }
    }
}

回答1:

String interpolation cannot be used to set the name of a variable:

day\(i)View.isHidden // does not work

Your best bet is to use an outlet collection to define all your day views.

Instead of this:

@IBOutlet var day1View: UITextField!
@IBOutlet var day2View: UITextField!
@IBOutlet var day3View: UITextField!
//...

Do this:

@IBOutlet var dayViews: [UITextField]!

Then you can write your loop like this:

for i in 0...noOfDays-1
{
    dayViews[i].isHidden = false
}

Note that to do this, you'll need to delete the existing outlets and reconnect them.

If you're using a storyboard, then when you Control-drag from your first text field to your class file, select Outlet Collection for the Connection type and name it dayViews. To add the remaining text fields to the collection, just Control-drag from each one to the dayViews var in your class file.