在 x 数量的元素上将 isHidden 设置为 false [英] Setting isHidden to false on x amount of elements

查看:23
本文介绍了在 x 数量的元素上将 isHidden 设置为 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据用户在文本字段中的输入来取消隐藏 n 个元素.

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

因此,用户在文本字段中输入 1 - 5 之间的数字,然后单击调用 createSplit 的提交.如您所见,它取消隐藏视图,然后我希望它循环 x(x 是用户输入的数字)次数以取消隐藏 day(i)View 文本字段

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

推荐答案

字符串插值不能用于设置变量名:

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.

取而代之的是:

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

这样做:

@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.

如果您使用的是故事板,那么当您按住 Control 键从第一个文本字段拖动到类文件时,选择 Outlet Collection 作为连接类型并将其命名为 dayViews.要将剩余的文本字段添加到集合中,只需按住 Control 键将每个字段拖到类文件中的 dayViews 变量即可.

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.

这篇关于在 x 数量的元素上将 isHidden 设置为 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆