1

i have one view and set multiple subviews on the view, my subviews is dynamically created, i want all subview in centre and auto resizable, so how can do it.

enter image description here

for(i=1; i<answer.characters.count; i++) {

             ansview = UIView(frame: CGRectMake(viewwidth-5, 10, 30, 30))

            ansview.layer.cornerRadius = 0.2 * btn.bounds.size.width
            ansview.backgroundColor = UIColor.grayColor()
            ansview.tag = i;

            viewAnswer.addSubview(ansview)

            viewwidth = viewwidth + 35
}

this type of output generated to this code, so how can do it i am new in swift. thanks...

ikbal
  • 1,114
  • 1
  • 11
  • 30
  • Have you considered UIStackView? You can [programmatically add views to it](http://stackoverflow.com/q/30728062/4151918). –  Jan 08 '16 at 07:46

2 Answers2

1

add one condition to set frame of view

if(i == 1)
  {   
     ansview = UIView(frame: CGRectMake((viewAnswer.frame.size.width/2) - (CGFloat(answer.characters.count)/2 * 35), 10, 30, 30))
  }
    else
   {
     ansview = UIView(frame: CGRectMake(viewwidth-5, 10, 30, 30))
   }
Jaydeep Patel
  • 1,699
  • 17
  • 30
0

Only with constraints It can't be achieved. Create virtual view in either sides of view collection and make widths equal

enter image description here

Accepted answer of this question might help you Evenly space multiple views within a container view

Community
  • 1
  • 1
Rajesh
  • 10,318
  • 16
  • 44
  • 64