在Swift中以编程方式隐藏TextFields?

时间:2017-02-16 05:51:55

标签: ios swift user-interface

根据UITextFields需要显示的选项,我有UILabel的下拉菜单列表。

UITextField
DropdownMenu
UITextField
UITextField

如上所述,它显示了启动应用程序。更改下拉菜单后需要显示标签。

UITextField
DropdownMenu
UILabel
UITextField
UITextField

我知道如何使用UILabel隐藏label.hidden = true。但是在隐藏之后,UILabel仍然占据了空间。之后只显示了两个UITextField。如果隐藏标签后有任何动态改变位置的方法。

我已经以编程方式用于创建TextFields和Labels:

let textField1 = UITextField(frame: CGRect(x: 20, y: 10, width: UIApplication.shared.statusBarFrame.size.width - 40, height:45))
let textField2 = UITextField(frame: CGRect(x: 20, y: textField1.frame.origin.y + textField1.frame.size.height + 10, width: UIApplication.shared.statusBarFrame.size.width - 40, height: 45))
let button = UIButton(frame: CGRect(x: 20, y: textField2.frame.origin.y + textField2.frame.size.height + 10, width: UIApplication.shared.statusBarFrame.size.width - 40, height: 45))
let label1 = UILabel(frame: CGRect(x: 20, y: button.frame.origin.y + button.frame.size.height + 10, width: UIApplication.shared.statusBarFrame.size.width - 40, height: 45))
let textField3 = UITextField(frame: CGRect(x: 20, y: label1.frame.origin.y + label1.frame.size.height + 10, width: UIApplication.shared.statusBarFrame.size.width - 40, height: 45))
let textField4 = UITextField(frame: CGRect(x: 20, y: textField3.frame.origin.y + textField3.frame.size.height + 10, width: UIApplication.shared.statusBarFrame.size.width - 40, height: 45))

3 个答案:

答案 0 :(得分:0)

根据您的要求,您似乎需要使用UIStackView控件来解决此问题:

  

所以在隐藏之后但那个地方有空

如果一个或多个子控件添加/删除,UIStackView会自行调整,具体取决于您设置为UIStackView的参数。看看这些链接如何使用它:

iOS 9: Getting Started with UIStackView

UIStackView Tutorial: Introducing Stack Views

答案 1 :(得分:0)

  

@NeverHopeless是对的,UIStackView是完美的解决方案,这里是   如何以编程方式使用它:

override func viewDidAppear(_ animated: Bool) {

    let subviewArray = [TextFields1, TextFields2, Button, Label1, TextFields3, TextFields4]
    let stackView = UIStackView(arrangedSubviews: subviewArray)
    stackView.axis = .Vertical  // It can also align horizontally
    stackView.distribution = .FillEqually  // You can try other options
    stackView.alignment = .Fill  // You can try other options
    stackView.spacing = 5  // Bigger spacing means larger distance between subviews
    stackView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(stackView)

}

有关以编程方式添加UIStackView的详情,请参阅此处:https://makeapppie.com/2015/11/11/how-to-add-stack-views-programmatically-and-almost-avoid-autolayout/

答案 2 :(得分:0)

StackView是一种解决问题的好方法。

但如果您不想更改代码。您可以更改标签的高度= 0

label1.frame.size = CGSize(width: 0, height: 0)

但我仍然建议使用stackView,因为它更具动态性