AutoLayout with hidden UIViews?

后端 未结 13 1384
南方客
南方客 2020-11-27 09:27

I feel like it\'s a fairly common paradigm to show/hide UIViews, most often UILabels, depending on business logic. My question is, what is the best

13条回答
  •  春和景丽
    2020-11-27 09:58

    My preferred method is very similar to that suggested by Jorge Arimany.

    I prefer to create multiple constraints. First create your constraints for when the second label is visible. Create an outlet for the constraint between button and the 2nd label (if you are using objc make sure its strong). This constraint determines the height between the button and the second label when it's visible.

    Then create another constraint that specifies the height between the button and the top label when the second button is hidden. Create an outlet to the second constraint and make sure this outlet has a strong pointer. Then uncheck the installed checkbox in interface builder, and make sure the first constraint's priority is lower than this second constraints priority.

    Finally when you hide the second label, toggle the .isActive property of these constraints and call setNeedsDisplay()

    And that's it, no Magic numbers, no math, if you have multiple constraints to turn on and off you can even use outlet collections to keep them organized by state. (AKA keep all the hidden constraints in one OutletCollection and the non-hidden ones in another and just iterate over each collection toggling their .isActive status).

    I know Ryan Romanchuk said he didn't want to use multiple constraints, but I feel like this isn't micromanage-y, and is simpler that dynamically creating views and constraints programmatically (which is what I think he was wanting to avoid if I'm reading the question right).

    I've created a simple example, I hope it's useful...

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var ToBeHiddenLabel: UILabel!
    
    
        @IBOutlet var hiddenConstraint: NSLayoutConstraint!
        @IBOutlet var notHiddenConstraint: NSLayoutConstraint!
    
    
        @IBAction func HideMiddleButton(_ sender: Any) {
    
            ToBeHiddenLabel.isHidden = !ToBeHiddenLabel.isHidden
            notHiddenConstraint.isActive = !notHiddenConstraint.isActive
            hiddenConstraint.isActive = !hiddenConstraint.isActive
    
            self.view.setNeedsDisplay()
        }
    }
    

提交回复
热议问题