Properly center uiviews inside their parentView





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm making a slot UIView(). i have subclassed UIView() and everything is working just fine.



Now i'm trying to use autolayout to support ipads too.



Here's what i want:



img1



What i have achieved:



public protocol GDTextSlotDelegate: class{
func onTextEntered(_ finalText: String)
}

@IBDesignable
final public class GDTextSlot: UIView, UIKeyInput {
public weak var delegate: GDTextSlotDelegate? = nil

/ ... /
}
@IBInspectable
public var numberOfSlots: Int = 4 {
didSet{
/ .. /
}
}

@IBInspectable
public var baseWidth: CGFloat = 30.0 {
didSet{
/ .. /
}
}


Also generating a new slot:



/// Calculate X position of slot and make sure
/// the whole group is always in center of the view
private func calcX() -> CGFloat{
return ((frame.width - (baseWidth * CGFloat(numberOfSlots))) / 2) + (CGFloat((currentSlot - 1)) * CGFloat(baseWidth))
}

private func calcFrame() -> CGRect{
return CGRect(x: calcX(), y: 0, width: baseWidth, height: frame.height)
}

/// Initiate a new label for the slot!
private var label: UILabel{
let lbl: UILabel = UILabel()
lbl.frame = calcFrame()
lbl.text = "_"
lbl.textColor = UIColor.white
lbl.font = UIFont.boldSystemFont(ofSize: 25)
lbl.textAlignment = .center
lbl.tag = currentSlot

return lbl
}


Final step:



public func generateSlots(){
for index in 1...numberOfSlots{
currentSlot = index
addSubview(label)
}
currentSlot = 1
}


But, Adding AutoLayout on the storyboard makes the view wide on ipad, which's fine. but the slots doesn't center.



Here's my debug hierarchy on iPad:
s



I'd appreciate any solution with either with code or autolayout, Thanks










share|improve this question























  • You need set horizontal view center equal parent view center and then change multiplier for constraint

    – canister_exister
    Nov 26 '18 at 18:08











  • Well, thank you. I wouldn't ask if i knew to :D i'm new to autolayout

    – Rawand Ahmad
    Nov 26 '18 at 18:10













  • @RawandAhmad Is frame the frame of the parent view?

    – Xcoder
    Nov 26 '18 at 18:59













  • @RawandAhmad Do you mind posting an image of the result of your current code(not storyboard)?

    – Xcoder
    Nov 26 '18 at 19:01











  • @RawandAhmad Check my answer, and let me know if it works for you :)

    – Xcoder
    Dec 8 '18 at 1:25


















0















I'm making a slot UIView(). i have subclassed UIView() and everything is working just fine.



Now i'm trying to use autolayout to support ipads too.



Here's what i want:



img1



What i have achieved:



public protocol GDTextSlotDelegate: class{
func onTextEntered(_ finalText: String)
}

@IBDesignable
final public class GDTextSlot: UIView, UIKeyInput {
public weak var delegate: GDTextSlotDelegate? = nil

/ ... /
}
@IBInspectable
public var numberOfSlots: Int = 4 {
didSet{
/ .. /
}
}

@IBInspectable
public var baseWidth: CGFloat = 30.0 {
didSet{
/ .. /
}
}


Also generating a new slot:



/// Calculate X position of slot and make sure
/// the whole group is always in center of the view
private func calcX() -> CGFloat{
return ((frame.width - (baseWidth * CGFloat(numberOfSlots))) / 2) + (CGFloat((currentSlot - 1)) * CGFloat(baseWidth))
}

private func calcFrame() -> CGRect{
return CGRect(x: calcX(), y: 0, width: baseWidth, height: frame.height)
}

/// Initiate a new label for the slot!
private var label: UILabel{
let lbl: UILabel = UILabel()
lbl.frame = calcFrame()
lbl.text = "_"
lbl.textColor = UIColor.white
lbl.font = UIFont.boldSystemFont(ofSize: 25)
lbl.textAlignment = .center
lbl.tag = currentSlot

return lbl
}


Final step:



public func generateSlots(){
for index in 1...numberOfSlots{
currentSlot = index
addSubview(label)
}
currentSlot = 1
}


But, Adding AutoLayout on the storyboard makes the view wide on ipad, which's fine. but the slots doesn't center.



Here's my debug hierarchy on iPad:
s



I'd appreciate any solution with either with code or autolayout, Thanks










share|improve this question























  • You need set horizontal view center equal parent view center and then change multiplier for constraint

    – canister_exister
    Nov 26 '18 at 18:08











  • Well, thank you. I wouldn't ask if i knew to :D i'm new to autolayout

    – Rawand Ahmad
    Nov 26 '18 at 18:10













  • @RawandAhmad Is frame the frame of the parent view?

    – Xcoder
    Nov 26 '18 at 18:59













  • @RawandAhmad Do you mind posting an image of the result of your current code(not storyboard)?

    – Xcoder
    Nov 26 '18 at 19:01











  • @RawandAhmad Check my answer, and let me know if it works for you :)

    – Xcoder
    Dec 8 '18 at 1:25














0












0








0








I'm making a slot UIView(). i have subclassed UIView() and everything is working just fine.



Now i'm trying to use autolayout to support ipads too.



Here's what i want:



img1



What i have achieved:



public protocol GDTextSlotDelegate: class{
func onTextEntered(_ finalText: String)
}

@IBDesignable
final public class GDTextSlot: UIView, UIKeyInput {
public weak var delegate: GDTextSlotDelegate? = nil

/ ... /
}
@IBInspectable
public var numberOfSlots: Int = 4 {
didSet{
/ .. /
}
}

@IBInspectable
public var baseWidth: CGFloat = 30.0 {
didSet{
/ .. /
}
}


Also generating a new slot:



/// Calculate X position of slot and make sure
/// the whole group is always in center of the view
private func calcX() -> CGFloat{
return ((frame.width - (baseWidth * CGFloat(numberOfSlots))) / 2) + (CGFloat((currentSlot - 1)) * CGFloat(baseWidth))
}

private func calcFrame() -> CGRect{
return CGRect(x: calcX(), y: 0, width: baseWidth, height: frame.height)
}

/// Initiate a new label for the slot!
private var label: UILabel{
let lbl: UILabel = UILabel()
lbl.frame = calcFrame()
lbl.text = "_"
lbl.textColor = UIColor.white
lbl.font = UIFont.boldSystemFont(ofSize: 25)
lbl.textAlignment = .center
lbl.tag = currentSlot

return lbl
}


Final step:



public func generateSlots(){
for index in 1...numberOfSlots{
currentSlot = index
addSubview(label)
}
currentSlot = 1
}


But, Adding AutoLayout on the storyboard makes the view wide on ipad, which's fine. but the slots doesn't center.



Here's my debug hierarchy on iPad:
s



I'd appreciate any solution with either with code or autolayout, Thanks










share|improve this question














I'm making a slot UIView(). i have subclassed UIView() and everything is working just fine.



Now i'm trying to use autolayout to support ipads too.



Here's what i want:



img1



What i have achieved:



public protocol GDTextSlotDelegate: class{
func onTextEntered(_ finalText: String)
}

@IBDesignable
final public class GDTextSlot: UIView, UIKeyInput {
public weak var delegate: GDTextSlotDelegate? = nil

/ ... /
}
@IBInspectable
public var numberOfSlots: Int = 4 {
didSet{
/ .. /
}
}

@IBInspectable
public var baseWidth: CGFloat = 30.0 {
didSet{
/ .. /
}
}


Also generating a new slot:



/// Calculate X position of slot and make sure
/// the whole group is always in center of the view
private func calcX() -> CGFloat{
return ((frame.width - (baseWidth * CGFloat(numberOfSlots))) / 2) + (CGFloat((currentSlot - 1)) * CGFloat(baseWidth))
}

private func calcFrame() -> CGRect{
return CGRect(x: calcX(), y: 0, width: baseWidth, height: frame.height)
}

/// Initiate a new label for the slot!
private var label: UILabel{
let lbl: UILabel = UILabel()
lbl.frame = calcFrame()
lbl.text = "_"
lbl.textColor = UIColor.white
lbl.font = UIFont.boldSystemFont(ofSize: 25)
lbl.textAlignment = .center
lbl.tag = currentSlot

return lbl
}


Final step:



public func generateSlots(){
for index in 1...numberOfSlots{
currentSlot = index
addSubview(label)
}
currentSlot = 1
}


But, Adding AutoLayout on the storyboard makes the view wide on ipad, which's fine. but the slots doesn't center.



Here's my debug hierarchy on iPad:
s



I'd appreciate any solution with either with code or autolayout, Thanks







ios swift






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 26 '18 at 18:04









Rawand AhmadRawand Ahmad

3918




3918













  • You need set horizontal view center equal parent view center and then change multiplier for constraint

    – canister_exister
    Nov 26 '18 at 18:08











  • Well, thank you. I wouldn't ask if i knew to :D i'm new to autolayout

    – Rawand Ahmad
    Nov 26 '18 at 18:10













  • @RawandAhmad Is frame the frame of the parent view?

    – Xcoder
    Nov 26 '18 at 18:59













  • @RawandAhmad Do you mind posting an image of the result of your current code(not storyboard)?

    – Xcoder
    Nov 26 '18 at 19:01











  • @RawandAhmad Check my answer, and let me know if it works for you :)

    – Xcoder
    Dec 8 '18 at 1:25



















  • You need set horizontal view center equal parent view center and then change multiplier for constraint

    – canister_exister
    Nov 26 '18 at 18:08











  • Well, thank you. I wouldn't ask if i knew to :D i'm new to autolayout

    – Rawand Ahmad
    Nov 26 '18 at 18:10













  • @RawandAhmad Is frame the frame of the parent view?

    – Xcoder
    Nov 26 '18 at 18:59













  • @RawandAhmad Do you mind posting an image of the result of your current code(not storyboard)?

    – Xcoder
    Nov 26 '18 at 19:01











  • @RawandAhmad Check my answer, and let me know if it works for you :)

    – Xcoder
    Dec 8 '18 at 1:25

















You need set horizontal view center equal parent view center and then change multiplier for constraint

– canister_exister
Nov 26 '18 at 18:08





You need set horizontal view center equal parent view center and then change multiplier for constraint

– canister_exister
Nov 26 '18 at 18:08













Well, thank you. I wouldn't ask if i knew to :D i'm new to autolayout

– Rawand Ahmad
Nov 26 '18 at 18:10







Well, thank you. I wouldn't ask if i knew to :D i'm new to autolayout

– Rawand Ahmad
Nov 26 '18 at 18:10















@RawandAhmad Is frame the frame of the parent view?

– Xcoder
Nov 26 '18 at 18:59







@RawandAhmad Is frame the frame of the parent view?

– Xcoder
Nov 26 '18 at 18:59















@RawandAhmad Do you mind posting an image of the result of your current code(not storyboard)?

– Xcoder
Nov 26 '18 at 19:01





@RawandAhmad Do you mind posting an image of the result of your current code(not storyboard)?

– Xcoder
Nov 26 '18 at 19:01













@RawandAhmad Check my answer, and let me know if it works for you :)

– Xcoder
Dec 8 '18 at 1:25





@RawandAhmad Check my answer, and let me know if it works for you :)

– Xcoder
Dec 8 '18 at 1:25












3 Answers
3






active

oldest

votes


















2














@canister_exister has a good solution for the storyboard approach. Doing it in code is pretty simple, too. In your case, use UIStackView:



public func generateSlots(){ 
//Stack View
var stackView = UIStackView()

stackView.axis = UILayoutConstraintAxis.horizontal
stackView.distribution = UIStackViewDistributionEqualSpacing
stackView.alignment = UIStackViewAlignmentCenter
stackView.spacing = //spacing between each label
for index in 1...numberOfSlots{
currentSlot = index
var slotLabel = UILabel()
//customize your label here: don't need x and y
//these are width and height constraints for each label
view3.heightAnchor.constraint(equalToConstant: 20).isActive = true
view3.widthAnchor.constraint(equalToConstant: baseHeight).isActive = true
stackView.addArrangedSubview(label)
}
currentSlot = 1

stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
}





share|improve this answer































    2














    First set constraints for each child view
    enter image description here



    Second for each child view change Align Center X Multiplier



    enter image description here



    Multipliers should be 0.25 for first, 0.75 for second, 1.25 for third and 1.75 for fours






    share|improve this answer
























    • Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

      – Rawand Ahmad
      Nov 26 '18 at 18:19











    • Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

      – canister_exister
      Nov 26 '18 at 18:21











    • @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

      – J. Doe
      Nov 26 '18 at 19:46



















    2














    When you have an equal arrangement of some arbitrary number of objects like this, use a UIStackView. This screen shot shows an example:



    enter image description here



    The stack view is a horizontal stack view with center alignment and fill equally distribution. The stack view has a constraint horizontally centering it in its superview (and an arbitrary height constraint and top constraint, both irrelevant for this example). That causes its arranged subviews — the slot views — to be equally spaced and sized and the whole thing centered in the stack view's superview.



    Let's analyze how we get the specific results that we get.




    • The heights of the slot views are determined by their height constraints.


    • The spacing between the slot views is determined by the spacing setting of the stack view.


    • Thus, the only thing left to specify is the width of the slot views; that is set by the width constraint of the stack view itself. Knowing the desired width of a slot view, you just multiply that width by the number of slot views, multiply the stack view spacing by one less than the number of slot views, add those two together, and set the stack view width constraint constant to that.



    The slot views thus end up looking exactly the same, and centered horizontally in their superview, no matter what size the superview is. And the really cool part is that we can increase or decrease the number of slot views and it all continues to work perfectly, because the stack view does all the work of arranging them.






    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%2f53486696%2fproperly-center-uiviews-inside-their-parentview%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









      2














      @canister_exister has a good solution for the storyboard approach. Doing it in code is pretty simple, too. In your case, use UIStackView:



      public func generateSlots(){ 
      //Stack View
      var stackView = UIStackView()

      stackView.axis = UILayoutConstraintAxis.horizontal
      stackView.distribution = UIStackViewDistributionEqualSpacing
      stackView.alignment = UIStackViewAlignmentCenter
      stackView.spacing = //spacing between each label
      for index in 1...numberOfSlots{
      currentSlot = index
      var slotLabel = UILabel()
      //customize your label here: don't need x and y
      //these are width and height constraints for each label
      view3.heightAnchor.constraint(equalToConstant: 20).isActive = true
      view3.widthAnchor.constraint(equalToConstant: baseHeight).isActive = true
      stackView.addArrangedSubview(label)
      }
      currentSlot = 1

      stackView.translatesAutoresizingMaskIntoConstraints = false
      view.addSubview(stackView)
      }





      share|improve this answer




























        2














        @canister_exister has a good solution for the storyboard approach. Doing it in code is pretty simple, too. In your case, use UIStackView:



        public func generateSlots(){ 
        //Stack View
        var stackView = UIStackView()

        stackView.axis = UILayoutConstraintAxis.horizontal
        stackView.distribution = UIStackViewDistributionEqualSpacing
        stackView.alignment = UIStackViewAlignmentCenter
        stackView.spacing = //spacing between each label
        for index in 1...numberOfSlots{
        currentSlot = index
        var slotLabel = UILabel()
        //customize your label here: don't need x and y
        //these are width and height constraints for each label
        view3.heightAnchor.constraint(equalToConstant: 20).isActive = true
        view3.widthAnchor.constraint(equalToConstant: baseHeight).isActive = true
        stackView.addArrangedSubview(label)
        }
        currentSlot = 1

        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)
        }





        share|improve this answer


























          2












          2








          2







          @canister_exister has a good solution for the storyboard approach. Doing it in code is pretty simple, too. In your case, use UIStackView:



          public func generateSlots(){ 
          //Stack View
          var stackView = UIStackView()

          stackView.axis = UILayoutConstraintAxis.horizontal
          stackView.distribution = UIStackViewDistributionEqualSpacing
          stackView.alignment = UIStackViewAlignmentCenter
          stackView.spacing = //spacing between each label
          for index in 1...numberOfSlots{
          currentSlot = index
          var slotLabel = UILabel()
          //customize your label here: don't need x and y
          //these are width and height constraints for each label
          view3.heightAnchor.constraint(equalToConstant: 20).isActive = true
          view3.widthAnchor.constraint(equalToConstant: baseHeight).isActive = true
          stackView.addArrangedSubview(label)
          }
          currentSlot = 1

          stackView.translatesAutoresizingMaskIntoConstraints = false
          view.addSubview(stackView)
          }





          share|improve this answer













          @canister_exister has a good solution for the storyboard approach. Doing it in code is pretty simple, too. In your case, use UIStackView:



          public func generateSlots(){ 
          //Stack View
          var stackView = UIStackView()

          stackView.axis = UILayoutConstraintAxis.horizontal
          stackView.distribution = UIStackViewDistributionEqualSpacing
          stackView.alignment = UIStackViewAlignmentCenter
          stackView.spacing = //spacing between each label
          for index in 1...numberOfSlots{
          currentSlot = index
          var slotLabel = UILabel()
          //customize your label here: don't need x and y
          //these are width and height constraints for each label
          view3.heightAnchor.constraint(equalToConstant: 20).isActive = true
          view3.widthAnchor.constraint(equalToConstant: baseHeight).isActive = true
          stackView.addArrangedSubview(label)
          }
          currentSlot = 1

          stackView.translatesAutoresizingMaskIntoConstraints = false
          view.addSubview(stackView)
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 26 '18 at 22:09









          XcoderXcoder

          98621124




          98621124

























              2














              First set constraints for each child view
              enter image description here



              Second for each child view change Align Center X Multiplier



              enter image description here



              Multipliers should be 0.25 for first, 0.75 for second, 1.25 for third and 1.75 for fours






              share|improve this answer
























              • Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

                – Rawand Ahmad
                Nov 26 '18 at 18:19











              • Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

                – canister_exister
                Nov 26 '18 at 18:21











              • @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

                – J. Doe
                Nov 26 '18 at 19:46
















              2














              First set constraints for each child view
              enter image description here



              Second for each child view change Align Center X Multiplier



              enter image description here



              Multipliers should be 0.25 for first, 0.75 for second, 1.25 for third and 1.75 for fours






              share|improve this answer
























              • Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

                – Rawand Ahmad
                Nov 26 '18 at 18:19











              • Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

                – canister_exister
                Nov 26 '18 at 18:21











              • @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

                – J. Doe
                Nov 26 '18 at 19:46














              2












              2








              2







              First set constraints for each child view
              enter image description here



              Second for each child view change Align Center X Multiplier



              enter image description here



              Multipliers should be 0.25 for first, 0.75 for second, 1.25 for third and 1.75 for fours






              share|improve this answer













              First set constraints for each child view
              enter image description here



              Second for each child view change Align Center X Multiplier



              enter image description here



              Multipliers should be 0.25 for first, 0.75 for second, 1.25 for third and 1.75 for fours







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 26 '18 at 18:17









              canister_existercanister_exister

              133111




              133111













              • Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

                – Rawand Ahmad
                Nov 26 '18 at 18:19











              • Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

                – canister_exister
                Nov 26 '18 at 18:21











              • @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

                – J. Doe
                Nov 26 '18 at 19:46



















              • Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

                – Rawand Ahmad
                Nov 26 '18 at 18:19











              • Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

                – canister_exister
                Nov 26 '18 at 18:21











              • @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

                – J. Doe
                Nov 26 '18 at 19:46

















              Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

              – Rawand Ahmad
              Nov 26 '18 at 18:19





              Thank you so much for the answer, Can i do that in code? I can't really do it with storyboards

              – Rawand Ahmad
              Nov 26 '18 at 18:19













              Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

              – canister_exister
              Nov 26 '18 at 18:21





              Sure you can do it in code, but that's a lot of code and not fast. In storyboard it took me 2 mins and no code

              – canister_exister
              Nov 26 '18 at 18:21













              @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

              – J. Doe
              Nov 26 '18 at 19:46





              @RawandAhmad It shouldn't be to much hassle to mimic the pictures in code

              – J. Doe
              Nov 26 '18 at 19:46











              2














              When you have an equal arrangement of some arbitrary number of objects like this, use a UIStackView. This screen shot shows an example:



              enter image description here



              The stack view is a horizontal stack view with center alignment and fill equally distribution. The stack view has a constraint horizontally centering it in its superview (and an arbitrary height constraint and top constraint, both irrelevant for this example). That causes its arranged subviews — the slot views — to be equally spaced and sized and the whole thing centered in the stack view's superview.



              Let's analyze how we get the specific results that we get.




              • The heights of the slot views are determined by their height constraints.


              • The spacing between the slot views is determined by the spacing setting of the stack view.


              • Thus, the only thing left to specify is the width of the slot views; that is set by the width constraint of the stack view itself. Knowing the desired width of a slot view, you just multiply that width by the number of slot views, multiply the stack view spacing by one less than the number of slot views, add those two together, and set the stack view width constraint constant to that.



              The slot views thus end up looking exactly the same, and centered horizontally in their superview, no matter what size the superview is. And the really cool part is that we can increase or decrease the number of slot views and it all continues to work perfectly, because the stack view does all the work of arranging them.






              share|improve this answer






























                2














                When you have an equal arrangement of some arbitrary number of objects like this, use a UIStackView. This screen shot shows an example:



                enter image description here



                The stack view is a horizontal stack view with center alignment and fill equally distribution. The stack view has a constraint horizontally centering it in its superview (and an arbitrary height constraint and top constraint, both irrelevant for this example). That causes its arranged subviews — the slot views — to be equally spaced and sized and the whole thing centered in the stack view's superview.



                Let's analyze how we get the specific results that we get.




                • The heights of the slot views are determined by their height constraints.


                • The spacing between the slot views is determined by the spacing setting of the stack view.


                • Thus, the only thing left to specify is the width of the slot views; that is set by the width constraint of the stack view itself. Knowing the desired width of a slot view, you just multiply that width by the number of slot views, multiply the stack view spacing by one less than the number of slot views, add those two together, and set the stack view width constraint constant to that.



                The slot views thus end up looking exactly the same, and centered horizontally in their superview, no matter what size the superview is. And the really cool part is that we can increase or decrease the number of slot views and it all continues to work perfectly, because the stack view does all the work of arranging them.






                share|improve this answer




























                  2












                  2








                  2







                  When you have an equal arrangement of some arbitrary number of objects like this, use a UIStackView. This screen shot shows an example:



                  enter image description here



                  The stack view is a horizontal stack view with center alignment and fill equally distribution. The stack view has a constraint horizontally centering it in its superview (and an arbitrary height constraint and top constraint, both irrelevant for this example). That causes its arranged subviews — the slot views — to be equally spaced and sized and the whole thing centered in the stack view's superview.



                  Let's analyze how we get the specific results that we get.




                  • The heights of the slot views are determined by their height constraints.


                  • The spacing between the slot views is determined by the spacing setting of the stack view.


                  • Thus, the only thing left to specify is the width of the slot views; that is set by the width constraint of the stack view itself. Knowing the desired width of a slot view, you just multiply that width by the number of slot views, multiply the stack view spacing by one less than the number of slot views, add those two together, and set the stack view width constraint constant to that.



                  The slot views thus end up looking exactly the same, and centered horizontally in their superview, no matter what size the superview is. And the really cool part is that we can increase or decrease the number of slot views and it all continues to work perfectly, because the stack view does all the work of arranging them.






                  share|improve this answer















                  When you have an equal arrangement of some arbitrary number of objects like this, use a UIStackView. This screen shot shows an example:



                  enter image description here



                  The stack view is a horizontal stack view with center alignment and fill equally distribution. The stack view has a constraint horizontally centering it in its superview (and an arbitrary height constraint and top constraint, both irrelevant for this example). That causes its arranged subviews — the slot views — to be equally spaced and sized and the whole thing centered in the stack view's superview.



                  Let's analyze how we get the specific results that we get.




                  • The heights of the slot views are determined by their height constraints.


                  • The spacing between the slot views is determined by the spacing setting of the stack view.


                  • Thus, the only thing left to specify is the width of the slot views; that is set by the width constraint of the stack view itself. Knowing the desired width of a slot view, you just multiply that width by the number of slot views, multiply the stack view spacing by one less than the number of slot views, add those two together, and set the stack view width constraint constant to that.



                  The slot views thus end up looking exactly the same, and centered horizontally in their superview, no matter what size the superview is. And the really cool part is that we can increase or decrease the number of slot views and it all continues to work perfectly, because the stack view does all the work of arranging them.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 26 '18 at 21:22

























                  answered Nov 26 '18 at 20:56









                  mattmatt

                  335k47550747




                  335k47550747






























                      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%2f53486696%2fproperly-center-uiviews-inside-their-parentview%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

                      To store a contact into the json file from server.js file using a class in NodeJS

                      Redirect URL with Chrome Remote Debugging Android Devices

                      Dieringhausen