Setting isHidden to false on x amount of elements

半世苍凉 提交于 2019-12-11 14:56:27

问题


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.



来源:https://stackoverflow.com/questions/49134422/setting-ishidden-to-false-on-x-amount-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!