How to make the view height resizable in Swift?












0















I have a custom UIView class where I'm creating a UIView and putting inside UILabel. Initially, I set UIView height equal to 60.0. But how can I do that my UIView height would resize with UILabel? For example if UILabel contains 5 linesof text UIView height will also increase to 200pt(for example).



Here is my class: https://gist.github.com/orkhanalizade/747dc4fd1eb9f228ac964fb4048125dc



I have tried



self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 60.0).isActive = true


but it did not help me
What I do wrong and how can I fix it?










share|improve this question























  • I have a couple ideas and am sure one will work, but looking at your code I'm confused... why are you adding this UILabel into your UIView? There's no other subviews, and I'd think that you'd just pin the label to it's actual superview. (And for that matter, a UILabel isn't generally updated by the user, a UITextfield or UITextarea is.) Last thought without more info fro you - have you looked into making your constraint a variable? If you are looking to change the height in code, that's a good way to do it.

    – dfd
    Nov 23 '18 at 23:35
















0















I have a custom UIView class where I'm creating a UIView and putting inside UILabel. Initially, I set UIView height equal to 60.0. But how can I do that my UIView height would resize with UILabel? For example if UILabel contains 5 linesof text UIView height will also increase to 200pt(for example).



Here is my class: https://gist.github.com/orkhanalizade/747dc4fd1eb9f228ac964fb4048125dc



I have tried



self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 60.0).isActive = true


but it did not help me
What I do wrong and how can I fix it?










share|improve this question























  • I have a couple ideas and am sure one will work, but looking at your code I'm confused... why are you adding this UILabel into your UIView? There's no other subviews, and I'd think that you'd just pin the label to it's actual superview. (And for that matter, a UILabel isn't generally updated by the user, a UITextfield or UITextarea is.) Last thought without more info fro you - have you looked into making your constraint a variable? If you are looking to change the height in code, that's a good way to do it.

    – dfd
    Nov 23 '18 at 23:35














0












0








0








I have a custom UIView class where I'm creating a UIView and putting inside UILabel. Initially, I set UIView height equal to 60.0. But how can I do that my UIView height would resize with UILabel? For example if UILabel contains 5 linesof text UIView height will also increase to 200pt(for example).



Here is my class: https://gist.github.com/orkhanalizade/747dc4fd1eb9f228ac964fb4048125dc



I have tried



self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 60.0).isActive = true


but it did not help me
What I do wrong and how can I fix it?










share|improve this question














I have a custom UIView class where I'm creating a UIView and putting inside UILabel. Initially, I set UIView height equal to 60.0. But how can I do that my UIView height would resize with UILabel? For example if UILabel contains 5 linesof text UIView height will also increase to 200pt(for example).



Here is my class: https://gist.github.com/orkhanalizade/747dc4fd1eb9f228ac964fb4048125dc



I have tried



self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 60.0).isActive = true


but it did not help me
What I do wrong and how can I fix it?







ios swift nslayoutconstraint






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 21:55









John DoeJohn Doe

176




176













  • I have a couple ideas and am sure one will work, but looking at your code I'm confused... why are you adding this UILabel into your UIView? There's no other subviews, and I'd think that you'd just pin the label to it's actual superview. (And for that matter, a UILabel isn't generally updated by the user, a UITextfield or UITextarea is.) Last thought without more info fro you - have you looked into making your constraint a variable? If you are looking to change the height in code, that's a good way to do it.

    – dfd
    Nov 23 '18 at 23:35



















  • I have a couple ideas and am sure one will work, but looking at your code I'm confused... why are you adding this UILabel into your UIView? There's no other subviews, and I'd think that you'd just pin the label to it's actual superview. (And for that matter, a UILabel isn't generally updated by the user, a UITextfield or UITextarea is.) Last thought without more info fro you - have you looked into making your constraint a variable? If you are looking to change the height in code, that's a good way to do it.

    – dfd
    Nov 23 '18 at 23:35

















I have a couple ideas and am sure one will work, but looking at your code I'm confused... why are you adding this UILabel into your UIView? There's no other subviews, and I'd think that you'd just pin the label to it's actual superview. (And for that matter, a UILabel isn't generally updated by the user, a UITextfield or UITextarea is.) Last thought without more info fro you - have you looked into making your constraint a variable? If you are looking to change the height in code, that's a good way to do it.

– dfd
Nov 23 '18 at 23:35





I have a couple ideas and am sure one will work, but looking at your code I'm confused... why are you adding this UILabel into your UIView? There's no other subviews, and I'd think that you'd just pin the label to it's actual superview. (And for that matter, a UILabel isn't generally updated by the user, a UITextfield or UITextarea is.) Last thought without more info fro you - have you looked into making your constraint a variable? If you are looking to change the height in code, that's a good way to do it.

– dfd
Nov 23 '18 at 23:35












3 Answers
3






active

oldest

votes


















0














Since you are resizing the constants, you may want to use layoutIfNeeded(). It will force update the constraints in the view. You can read more about it in Apple's documentation.






share|improve this answer































    0














    Just calculate the height according to text and update height constraint of UIView with UIView.animate() method.






    share|improve this answer































      0














      Couple notes...



      1) In general, a view should not set its own frame. What happens if you want to add MyView as a subview of another view? Setting its frame as you have:



      width: UIScreen.main.bounds.width - 16.0


      will not give you the desired results.



      2) You do not need:



      self.addConstraints(constraints)


      3) I find it helpful to give elements different, obvious background colors -- makes it easy to see what the frames are doing.



      Here is an edited version of your gist, along with a view controller to add / display it:



      import UIKit

      class MyView: UIView {
      var label: UILabel!

      var text: String? {
      didSet {
      label.text = text
      }
      }

      var cornerRadius: CGFloat = 0.0 {
      didSet {
      self.layer.cornerRadius = self.cornerRadius
      self.layer.masksToBounds = true
      }
      }

      var textColor: UIColor = UIColor.black {
      didSet {
      label.textColor = textColor
      }
      }

      var isTextCentered: Bool = false {
      didSet {
      self.label.textAlignment = isTextCentered ? .center : .left
      }
      }

      init() {
      // we'll be using constraints, so no need to set a frame
      super.init(frame: CGRect.zero)
      initialize()
      }

      required init?(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
      }

      fileprivate func initialize() {

      label = UILabel()
      label.translatesAutoresizingMaskIntoConstraints = false
      label.numberOfLines = 0

      self.addSubview(label)

      let constraints = [
      NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
      NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
      NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0),
      NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0)
      ]
      NSLayoutConstraint.activate(constraints)

      // so we can see self's frame
      self.backgroundColor = .red

      // so we can see label's frame
      label.backgroundColor = .yellow

      }
      }

      class ViewController: UIViewController {

      override func viewDidLoad() {
      super.viewDidLoad()

      // instantiate the custom view
      let v = MyView()

      // we'll be using constraints
      v.translatesAutoresizingMaskIntoConstraints = false

      // add the view
      view.addSubview(v)

      NSLayoutConstraint.activate([
      // constrain Top: 60 / Leading: 8 / Trailing: -8
      v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
      v.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8.0),
      v.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8.0),

      // constrain height >= 60
      v.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0),
      ])

      // add 10 lines of text
      v.text = (1...10).map({ "Line ($0)" }).joined(separator: "n")

      }

      }


      And the result:



      enter image description here






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453309%2fhow-to-make-the-view-height-resizable-in-swift%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Since you are resizing the constants, you may want to use layoutIfNeeded(). It will force update the constraints in the view. You can read more about it in Apple's documentation.






        share|improve this answer




























          0














          Since you are resizing the constants, you may want to use layoutIfNeeded(). It will force update the constraints in the view. You can read more about it in Apple's documentation.






          share|improve this answer


























            0












            0








            0







            Since you are resizing the constants, you may want to use layoutIfNeeded(). It will force update the constraints in the view. You can read more about it in Apple's documentation.






            share|improve this answer













            Since you are resizing the constants, you may want to use layoutIfNeeded(). It will force update the constraints in the view. You can read more about it in Apple's documentation.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 23 '18 at 22:01









            Renzo TissoniRenzo Tissoni

            8117




            8117

























                0














                Just calculate the height according to text and update height constraint of UIView with UIView.animate() method.






                share|improve this answer




























                  0














                  Just calculate the height according to text and update height constraint of UIView with UIView.animate() method.






                  share|improve this answer


























                    0












                    0








                    0







                    Just calculate the height according to text and update height constraint of UIView with UIView.animate() method.






                    share|improve this answer













                    Just calculate the height according to text and update height constraint of UIView with UIView.animate() method.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 24 '18 at 6:00









                    iDev750iDev750

                    5961316




                    5961316























                        0














                        Couple notes...



                        1) In general, a view should not set its own frame. What happens if you want to add MyView as a subview of another view? Setting its frame as you have:



                        width: UIScreen.main.bounds.width - 16.0


                        will not give you the desired results.



                        2) You do not need:



                        self.addConstraints(constraints)


                        3) I find it helpful to give elements different, obvious background colors -- makes it easy to see what the frames are doing.



                        Here is an edited version of your gist, along with a view controller to add / display it:



                        import UIKit

                        class MyView: UIView {
                        var label: UILabel!

                        var text: String? {
                        didSet {
                        label.text = text
                        }
                        }

                        var cornerRadius: CGFloat = 0.0 {
                        didSet {
                        self.layer.cornerRadius = self.cornerRadius
                        self.layer.masksToBounds = true
                        }
                        }

                        var textColor: UIColor = UIColor.black {
                        didSet {
                        label.textColor = textColor
                        }
                        }

                        var isTextCentered: Bool = false {
                        didSet {
                        self.label.textAlignment = isTextCentered ? .center : .left
                        }
                        }

                        init() {
                        // we'll be using constraints, so no need to set a frame
                        super.init(frame: CGRect.zero)
                        initialize()
                        }

                        required init?(coder aDecoder: NSCoder) {
                        fatalError("init(coder:) has not been implemented")
                        }

                        fileprivate func initialize() {

                        label = UILabel()
                        label.translatesAutoresizingMaskIntoConstraints = false
                        label.numberOfLines = 0

                        self.addSubview(label)

                        let constraints = [
                        NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
                        NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
                        NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0),
                        NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0)
                        ]
                        NSLayoutConstraint.activate(constraints)

                        // so we can see self's frame
                        self.backgroundColor = .red

                        // so we can see label's frame
                        label.backgroundColor = .yellow

                        }
                        }

                        class ViewController: UIViewController {

                        override func viewDidLoad() {
                        super.viewDidLoad()

                        // instantiate the custom view
                        let v = MyView()

                        // we'll be using constraints
                        v.translatesAutoresizingMaskIntoConstraints = false

                        // add the view
                        view.addSubview(v)

                        NSLayoutConstraint.activate([
                        // constrain Top: 60 / Leading: 8 / Trailing: -8
                        v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
                        v.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8.0),
                        v.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8.0),

                        // constrain height >= 60
                        v.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0),
                        ])

                        // add 10 lines of text
                        v.text = (1...10).map({ "Line ($0)" }).joined(separator: "n")

                        }

                        }


                        And the result:



                        enter image description here






                        share|improve this answer




























                          0














                          Couple notes...



                          1) In general, a view should not set its own frame. What happens if you want to add MyView as a subview of another view? Setting its frame as you have:



                          width: UIScreen.main.bounds.width - 16.0


                          will not give you the desired results.



                          2) You do not need:



                          self.addConstraints(constraints)


                          3) I find it helpful to give elements different, obvious background colors -- makes it easy to see what the frames are doing.



                          Here is an edited version of your gist, along with a view controller to add / display it:



                          import UIKit

                          class MyView: UIView {
                          var label: UILabel!

                          var text: String? {
                          didSet {
                          label.text = text
                          }
                          }

                          var cornerRadius: CGFloat = 0.0 {
                          didSet {
                          self.layer.cornerRadius = self.cornerRadius
                          self.layer.masksToBounds = true
                          }
                          }

                          var textColor: UIColor = UIColor.black {
                          didSet {
                          label.textColor = textColor
                          }
                          }

                          var isTextCentered: Bool = false {
                          didSet {
                          self.label.textAlignment = isTextCentered ? .center : .left
                          }
                          }

                          init() {
                          // we'll be using constraints, so no need to set a frame
                          super.init(frame: CGRect.zero)
                          initialize()
                          }

                          required init?(coder aDecoder: NSCoder) {
                          fatalError("init(coder:) has not been implemented")
                          }

                          fileprivate func initialize() {

                          label = UILabel()
                          label.translatesAutoresizingMaskIntoConstraints = false
                          label.numberOfLines = 0

                          self.addSubview(label)

                          let constraints = [
                          NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
                          NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
                          NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0),
                          NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0)
                          ]
                          NSLayoutConstraint.activate(constraints)

                          // so we can see self's frame
                          self.backgroundColor = .red

                          // so we can see label's frame
                          label.backgroundColor = .yellow

                          }
                          }

                          class ViewController: UIViewController {

                          override func viewDidLoad() {
                          super.viewDidLoad()

                          // instantiate the custom view
                          let v = MyView()

                          // we'll be using constraints
                          v.translatesAutoresizingMaskIntoConstraints = false

                          // add the view
                          view.addSubview(v)

                          NSLayoutConstraint.activate([
                          // constrain Top: 60 / Leading: 8 / Trailing: -8
                          v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
                          v.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8.0),
                          v.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8.0),

                          // constrain height >= 60
                          v.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0),
                          ])

                          // add 10 lines of text
                          v.text = (1...10).map({ "Line ($0)" }).joined(separator: "n")

                          }

                          }


                          And the result:



                          enter image description here






                          share|improve this answer


























                            0












                            0








                            0







                            Couple notes...



                            1) In general, a view should not set its own frame. What happens if you want to add MyView as a subview of another view? Setting its frame as you have:



                            width: UIScreen.main.bounds.width - 16.0


                            will not give you the desired results.



                            2) You do not need:



                            self.addConstraints(constraints)


                            3) I find it helpful to give elements different, obvious background colors -- makes it easy to see what the frames are doing.



                            Here is an edited version of your gist, along with a view controller to add / display it:



                            import UIKit

                            class MyView: UIView {
                            var label: UILabel!

                            var text: String? {
                            didSet {
                            label.text = text
                            }
                            }

                            var cornerRadius: CGFloat = 0.0 {
                            didSet {
                            self.layer.cornerRadius = self.cornerRadius
                            self.layer.masksToBounds = true
                            }
                            }

                            var textColor: UIColor = UIColor.black {
                            didSet {
                            label.textColor = textColor
                            }
                            }

                            var isTextCentered: Bool = false {
                            didSet {
                            self.label.textAlignment = isTextCentered ? .center : .left
                            }
                            }

                            init() {
                            // we'll be using constraints, so no need to set a frame
                            super.init(frame: CGRect.zero)
                            initialize()
                            }

                            required init?(coder aDecoder: NSCoder) {
                            fatalError("init(coder:) has not been implemented")
                            }

                            fileprivate func initialize() {

                            label = UILabel()
                            label.translatesAutoresizingMaskIntoConstraints = false
                            label.numberOfLines = 0

                            self.addSubview(label)

                            let constraints = [
                            NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
                            NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
                            NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0),
                            NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0)
                            ]
                            NSLayoutConstraint.activate(constraints)

                            // so we can see self's frame
                            self.backgroundColor = .red

                            // so we can see label's frame
                            label.backgroundColor = .yellow

                            }
                            }

                            class ViewController: UIViewController {

                            override func viewDidLoad() {
                            super.viewDidLoad()

                            // instantiate the custom view
                            let v = MyView()

                            // we'll be using constraints
                            v.translatesAutoresizingMaskIntoConstraints = false

                            // add the view
                            view.addSubview(v)

                            NSLayoutConstraint.activate([
                            // constrain Top: 60 / Leading: 8 / Trailing: -8
                            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
                            v.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8.0),
                            v.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8.0),

                            // constrain height >= 60
                            v.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0),
                            ])

                            // add 10 lines of text
                            v.text = (1...10).map({ "Line ($0)" }).joined(separator: "n")

                            }

                            }


                            And the result:



                            enter image description here






                            share|improve this answer













                            Couple notes...



                            1) In general, a view should not set its own frame. What happens if you want to add MyView as a subview of another view? Setting its frame as you have:



                            width: UIScreen.main.bounds.width - 16.0


                            will not give you the desired results.



                            2) You do not need:



                            self.addConstraints(constraints)


                            3) I find it helpful to give elements different, obvious background colors -- makes it easy to see what the frames are doing.



                            Here is an edited version of your gist, along with a view controller to add / display it:



                            import UIKit

                            class MyView: UIView {
                            var label: UILabel!

                            var text: String? {
                            didSet {
                            label.text = text
                            }
                            }

                            var cornerRadius: CGFloat = 0.0 {
                            didSet {
                            self.layer.cornerRadius = self.cornerRadius
                            self.layer.masksToBounds = true
                            }
                            }

                            var textColor: UIColor = UIColor.black {
                            didSet {
                            label.textColor = textColor
                            }
                            }

                            var isTextCentered: Bool = false {
                            didSet {
                            self.label.textAlignment = isTextCentered ? .center : .left
                            }
                            }

                            init() {
                            // we'll be using constraints, so no need to set a frame
                            super.init(frame: CGRect.zero)
                            initialize()
                            }

                            required init?(coder aDecoder: NSCoder) {
                            fatalError("init(coder:) has not been implemented")
                            }

                            fileprivate func initialize() {

                            label = UILabel()
                            label.translatesAutoresizingMaskIntoConstraints = false
                            label.numberOfLines = 0

                            self.addSubview(label)

                            let constraints = [
                            NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
                            NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
                            NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0),
                            NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0)
                            ]
                            NSLayoutConstraint.activate(constraints)

                            // so we can see self's frame
                            self.backgroundColor = .red

                            // so we can see label's frame
                            label.backgroundColor = .yellow

                            }
                            }

                            class ViewController: UIViewController {

                            override func viewDidLoad() {
                            super.viewDidLoad()

                            // instantiate the custom view
                            let v = MyView()

                            // we'll be using constraints
                            v.translatesAutoresizingMaskIntoConstraints = false

                            // add the view
                            view.addSubview(v)

                            NSLayoutConstraint.activate([
                            // constrain Top: 60 / Leading: 8 / Trailing: -8
                            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
                            v.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8.0),
                            v.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8.0),

                            // constrain height >= 60
                            v.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0),
                            ])

                            // add 10 lines of text
                            v.text = (1...10).map({ "Line ($0)" }).joined(separator: "n")

                            }

                            }


                            And the result:



                            enter image description here







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 27 '18 at 17:08









                            DonMagDonMag

                            16.7k21029




                            16.7k21029






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453309%2fhow-to-make-the-view-height-resizable-in-swift%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Wiesbaden

                                Marschland

                                Dieringhausen