Search code examples
swiftuiviewxcode7addsubview

Where to add subviews in a viewcontrollers lifecycle


For me it make sense to add subviews in viewDidLoad, because it gets call when the view load, but i can't do that with my subviews. I have subviews which frame depends on another already added subviews height and width, and height and width is not correct before viewDidAppear. So i add my subviews in viewDidAppear, but viewDidAppear gets call everytime the view appears which is bad. So for my solution right now i add my subviews in viewDidAppear and when view disappear I remove the subviews in viewDidDisappear. Is there another way to archieve this without I manual removing subviews from superview.

Example

override func viewDidAppear(animated: Bool) {

        print(PercentageView.frame.width)
        print(PercentageView.frame.height)
        CreateInfoRecipeLabels()//Add subviews
        CreateCircleDiagram() //Add subviews

    }

    override func viewDidDisappear(animated: Bool) {
        //When view disappear deallocate subviews
        for view in PercentageView.subviews {
            view.removeFromSuperview()
        }
    }

UPDATE - Tried this instead, but it is like it can't add subview before there is a frame?

    @IBOutlet weak var RecipeInfoContain: UIView!
var MinLabel: SMIconLabel?
    var Min = "15"

    override func viewDidLoad() {
        super.viewDidLoad()

        RecipeInfoContain.addSubview(MinLabel!)

        // Do any additional setup after loading the view.
    }

override func viewWillLayoutSubviews() {
        MinLabel = SMIconLabel(frame: CGRectMake(RecipeInfoContain.frame.width/4 - 50, RecipeInfoContain.frame.height/2 - 10, 100, 20))
        MinLabel!.text = Min + " min"
        //MinLabel.backgroundColor = UIColor.redColor()
        MinLabel!.font = UIFont(name: "OpenSans", size: 11)
        MinLabel!.textColor = UIColor.whiteColor()
        MinLabel!.icon = UIImage(named: "Clock")
        MinLabel!.clipsToBounds = true
        MinLabel!.iconPadding = 5
        MinLabel!.iconPosition = .Left
        MinLabel!.textAlignment = .Left
    }

Solution

  • Two thoughts:

    1. If you use autolayout to dictate the frame of the subviews, then you can add them in viewDidLoad and the autolayout engine will take care of sizing them appropriately.

      Just set translatesAutoresizingMaskIntoConstraints for the subviews to false and then add the appropriate constraints rather than setting frame values manually.

    2. If you really want to manually adjust the frames, you can add the subviews in viewDidLoad, but then adjust the frames in viewWillLayoutSubviews.