Search code examples
iosswiftxcodeconstraintsuilabel

Show Hide for UILabel over constraint not working as expected for height constraint


I have UILabel which I am showing and hiding on tapGesture. I have created label programatically and set constraint programatically only.

by default UILabel is visible with heightConstraint = 230 on tapGesture method I am making heightConstraint = 0 and its hiding label correctly. Again on tapGesture I need to show label, so when I tap again, I can see heightConstraint = 230 again, but label is not seen in UI.

What might be issue, only hide is working and show is not working.

Following is the code for tapGesture method where I am setting height constraints.

@objc func tapLabel(gesture: UITapGestureRecognizer) {
        print("tap working")
        isExpanded.toggle()
        if(isExpanded){
            NSLayoutConstraint.activate([
                reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
            ])
        }else{
            NSLayoutConstraint.activate([
                reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 0)
            ])
        }
    }

I tried to deactivate the constraint but not working.

Please find the screen shot attached.

  1. Default state when label is seen

enter image description here

  1. On Click, when label is hidden.

enter image description here

now after clicking again label is not showing.

Thanks in advance.


Solution

  • I just sorted the issue. The issue was I was declaring var heightCon:NSLayoutConstraint! as local.

    I just declare the same in Global.

    Following is the code sorted the issue.

    var heightCon:NSLayoutConstraint!
        @objc func tapLabel(gesture: UITapGestureRecognizer) {
            isExpanded.toggle()
            if let constraint = heightCon{
                constraint.isActive = false
            }
            heightCon = reminderBulletsLbl.heightAnchor.constraint(equalToConstant: isExpanded ? 230 : 0)
            heightCon.isActive = true
        }
    

    Thanks @Sh_Khan for the help.