skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. First you need to keep an instance of the height constraint don’t create new height constraint every time. like this

    var constraint: NSLayoutConstraint?
    

    and inside the viewDidLoad add this

    constraint = label.heightAnchor.constraint(equalToConstant: 250)
    constraint?.isActive = true
    

    then inside tapLabel function add

    constraint?.constant = isExpanded ? 20 : 250
    

    Second the most important thing when you make your height 0 you can’t tap it anymore because the label height is zero then how you can tap something has zero height if you make it 20 like the example i provided the label will be clickable if you want to hide the label completely maybe you need to take another approach than tapping the label

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search