user2365865
user2365865

Reputation:

Create new UI elements programmatically

I'd like to be able to create elements (like UIViews) when for example the user touches a button

NSMutableString *myVar = [NSMutableString stringWithFormat:@"_view%i", num];
UIView * newView = [self valueForKey:myVar];

but without adding all the

UIView * _view1;
UIView * _view2;
...

in the .h file (if only this is possible..)

Upvotes: 0

Views: 104

Answers (4)

iphondroid
iphondroid

Reputation: 500

You need not add your views in the .h file. Just instantiate before and where you add them

-(void) addButton
{
UIView *view = [self view];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:@"My Button" forState:UIControlStateNormal];

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 0, 0)];
[myLabel setText:@"My Label"];

[button1 sizeToFit];
[myLabel sizeToFit];

[view addSubview:button1];
[view addSubview:myLabel];
}

Upvotes: 0

Paul Dardeau
Paul Dardeau

Reputation: 2619

Here's sample code that should do what you want.

@interface MyViewController ()

@property (strong, nonatomic) NSMutableArray *listChildViews;

@end

@implementation MyViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.listChildViews = [[NSMutableArray alloc] init];
}

- (IBAction)addChildViewTapped:(id)sender
{
    int numChildViews = [self.listChildViews count];

    ++numChildViews;

    // add new child view
    NSString *labelForNewView = [NSString stringWithFormat:@"view %d", numChildViews];

    CGFloat labelHeight = 28.0;

    UILabel *childView = [[UILabel alloc] initWithFrame:CGRectMake(10, numChildViews*labelHeight, 120.0, labelHeight)];
    childView.text = labelForNewView;
    [self.listChildViews addObject:childView];
    [self.view addSubview:childView];
}

@end

Upvotes: 1

rptwsthi
rptwsthi

Reputation: 10172

Here is code implementation of pauls answer:

- (IBAction)userTouchedButton:(id)sender{
    for (int i = 0; i < 100; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        [view setBackgroundColor:[UIColor redColor]];//to distinguish theseViews from other views
        [view setTag:i];//to identified it later
        [_array insertObject:view atIndex:i];// globleMutble array
        [self.view addSubview:view];
    }
}

Upvotes: 0

Paul Dardeau
Paul Dardeau

Reputation: 2619

You can use an NSMutableArray to hold them. Each time you create a new view just add it to the array.

Upvotes: 1

Related Questions