Programmazione iPad / iPhone – Disegnare la UI (User Interface) dinamicamente a runtime senza utilizzare Interface Builder
In questo esempio di programmazione iPad/iPhone vedremo come disegnare la User Interface dinamicamente, senza l’utilizzo dell Interface Builder, durante l’esecuzione dell’applicazione, in particolare sfruttando il delegate “loadView” del ViewController.
Da Xcode create un progetto View-based Application e chiamiamolo “dynamicviews”.
Apriamo direttamente il file dynamicviewsViewController.m ed aggiungiamo il codice che segue al delegate loadView:
- (void)loadView {
//creazione dell’oggetto UIView
UIView *view =
[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
view.backgroundColor = [UIColor redColor];
//creazione della Label view
CGRect frame = CGRectMake(10, 15, 400, 20);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
// Settiamo una serie di proprietà per la Label
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:@"Verdana" size:18];
label.text = @”Questa Etichetta è creata dinamicamente!”;
label.tag = 1000;
//creazione Button view
frame = CGRectMake(60, 70, 300, 50);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@"Clikka qui!" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[button addTarget:self
action:@selector(buttonClicked: )
forControlEvents:UIControlEventTouchUpInside];
// Disegniamo i componenti sulla view
[view addSubview:label];
[view addSubview:button];
//associamo la View alla classe corrente
self.view = view;
[label release];
[button release];
}
Aggiungiamo inoltre un azione al click del bottone, che notifica attraverso una UIAlertView un messaggio di testo:
-(IBAction) buttonClicked: (id) sender{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@”Pulsante click!”
message:@”Ciao, ti piace questo esempio?!”
delegate:self
cancelButtonTitle:@”Chiudi”
otherButtonTitles:nil];
[alert show];
[alert release];
}
Questo è tutto.
