1

Hello I would like to ask how to create multiple views programmatically and show them on the screen, I have tried this but there is something missing.

int x,y;

x= 0;
y=50;

for (int i=0; i<4; i++)
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 300, 100)];

view.backgroundColor = [UIColor redColor];


[self.view addSubview: view];

    y+=40;
} 
2
  • which method do you have this code in? Commented Jun 4, 2015 at 10:33
  • which method do you use this in ? I'm trying to make multiple UIViews in swift but I thought making it like so would override the same and delete the previous one from superview? Commented Oct 26, 2016 at 17:41

3 Answers 3

2
int x,y,paddingX,widthOfView,HeightOfView;

x= 0;
y=50;
paddingX = 10;
widthOfView = 100;
HeightOfView = 100;

for (int i=0; i<4; i++){
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, widthOfView, HeightOfView)];
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview: view];

    y+= widthOfView + paddingX;
}

Following Code may help to you.

Sign up to request clarification or add additional context in comments.

Comments

0
int x,y;
x= 0;
y=50;

for (int i=0; i<4; i++)
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 300, 100)];

    view.backgroundColor = [UIColor redColor];
    view.layer.cornerRadius = 5.0f;
    [self.view addSubview: view];
    y+=140; //y for next view should be height of previous view and margin between view 
} 

3 Comments

Thank you, how to make them a rounded rectangle shape ?
Try to set view.layer.cornerRadius
Hello I would like to ask you how can I update the frame size while dragging it i have tried this code : { UITouch *touch = [touches anyObject]; CGPoint thisTouch = [touch locationInView:[touch view].superview]; CGPoint prevTouch = [touch previousLocationInView:[touch view].superview]; CGFloat dx = thisTouch.x - prevTouch.x; if ([touch view].frame.origin.x + dx < -500) { [touch view].frame = CGRectMake([touch view].frame.origin.x + dx, [touch view].frame.origin.y, [touch view].frame.size.width, [touch view].frame.size.height); }
0
  int x,y;

  x= 0;
  y=50
   for (int i=0; i<4; i++)
   {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, 30, 30)];

    view.backgroundColor = [UIColor redColor];
     y+=40;

    [self.view addSubview: view];    
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.