iosswiftuibuttoniboutletviewdidlayoutsubviews

Cannot unhide a button except in ViewDidLayoutSubviews()


I have a UIButton that should only be appearing sometimes. In the viewDidLayoutSubviews I did the following:

 override func viewDidLayoutSubviews() {
    super.viewWillLayoutSubviews()
    clearButtonOutlet.hidden = true

However, when I try to do clearButtonOutlet.hidden = false in other places, the button will not reappear.

At first I thought maybe my constraints were messed up but this makes the button reappear:

override func viewDidLayoutSubviews() {
    super.viewWillLayoutSubviews()
    clearButtonOutlet.hidden = true
    clearButtonOutlet.hidden = false

Why can I not make the button reappear in other places?

EDIT 1: Where I am trying to make the button reappear:

func textFieldDidBeginEditing(textField: UITextField) {

    //some stuff
    switch textField.tag {

        //tag = 3 is the when I want the clear button to show
    case 3:
        //launch the date picker
        launchDatePicker(textField)

        //once DatePicker is launched, show the clear button
        clearButtonOutlet.hidden = false
    default: break
    }

Solution

  • Just setting it hidden won't do everything, you need to get the view to redraw. I would set clearButton.hidden = true when you create the button not in viewDidLayout or it will always hide when the view lays out again (resize on iPad or landscape orientation). Then in your textFieldDidBeginEditing method I would set the clearButton.hidden = false like you have and then call view.setNeedsLayout() to force it to relayout and draw.