Rashad.Z
Rashad.Z

Reputation: 2604

Adding SubViews Programatically Below Each Other

I want to add a set of UITextFields programatically. The amount of UITextFields do not know and it will be created in a For Loop. I can perform this, but the problem is which created UILabels placed on top of each other. How can I place some constraints which are placed below each other.

currently my code is the following:

For Loop...
{
  let Description = UILabel(frame: CGRectMake(20, 100, 300, 40))
                    Description.font = UIFont.systemFontOfSize(18)
  ...
  self.view.addSubview(Description)
  // StackView.addSubview(Description)  
  // I TRIED ADDING A STACK VIEW BUT HAD THE SAME EFFECT.
}

Upvotes: 0

Views: 869

Answers (4)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

do like

Step-1

initially Create the Y coordinate and set the height as you like

  var y : CGFloat = 3

Step-2

 for var index1:Int = 0 ; index1 < yourArray.count ; index1++
            {

                        let timerLbl:UILabel = UILabel(frame: CGRectMake(5, y, self.view.frame.size.width, 35)) //UILabel(frame: CGRectMake(50, y, self.view.frame.size.width, 35))
                        timerLbl.textAlignment = .Center
                        timerLbl.textColor = UIColor.clearColor() 
                        timerLbl.text = "00:00"
                        timerLbl.tag =  index1 
                        self.view.addSubview(timerLbl)

                    // continue the other lables

                       // the following line increment your height 
                        y = y + 10 
                    }

Upvotes: 1

Dekel Maman
Dekel Maman

Reputation: 2097

I'm not in home but you should use code something like that:

var yRect : CGFloat = 100
let padding : CGFloat = 20
For Loop...
    {
     let Description = UILabel(frame: CGRectMake(20, yRect, 300, 40))
                    Description.font = UIFont.systemFontOfSize(18)
yRect += 40
...

self.view.addSubview(Description)
}

Upvotes: 1

Tejas Ardeshna
Tejas Ardeshna

Reputation: 4371

try this one

 var y = 100
    For Loop...
        {
                        let Description = UILabel(frame: CGRectMake(20, y, 300, 40))
    y = Description.Frame.size.height
                        Description.font = UIFont.systemFontOfSize(18)
    ...


        self.view.addSubview(Description)

        // StackView.addSubview(Description)  // I TRIED ADDING A STACK VIEW BUT HAD THE SAME EFFECT.


        }

Upvotes: 2

Nanoc
Nanoc

Reputation: 2381

You have to increment the Y value when you create the CGRect.

Store the Y value on an int variable and just increment it to your buttonHeight+desiredMargin on each iteration.

Hope this helps.

Upvotes: 1

Related Questions