Building a titleView programmatically with constraints (or generally constructing a view with constraints)

后端 未结 6 1799
长情又很酷
长情又很酷 2021-02-03 20:44

I\'m trying to build a titleView with constraints that looks like this:

\"titleView\"

I know how I would do

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-03 21:40

    I really needed constraints, so played around with it today. What I found that works is this:

        let v  = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        // add your views and set up all the constraints
    
        // This is the magic sauce!
        v.layoutIfNeeded()
        v.sizeToFit()
    
        // Now the frame is set (you can print it out)
        v.translatesAutoresizingMaskIntoConstraints = true // make nav bar happy
        navigationItem.titleView = v
    

    Works like a charm!

提交回复
热议问题