Objective-C: un’alternativa all’uso di CGRectMake

lunedì 27 luglio, 2009

CGRectMake() è una funzione (in realtà è un inline #define) molto usata soprattutto quando si creano da codice oggetti grafici o di interfaccia utente. Il suo utilizzo è quindi spesso legato all'inizializzazione di componenti UIKit, ma anche a semplici UIView o UIImageView. CGRectMake() restituisce una struct (struttura di tipo) CGRect:

Objective-C:
  1. struct CGRect {
  2.   CGPoint origin;
  3.   CGSize size;
  4. };
  5. typedef struct CGRect CGRect;

Che a sua volta è composta da due diverse struct CGPoint e CGSize:

Objective-C:
  1. struct CGPoint {
  2.   CGFloat x;
  3.   CGFloat y;
  4. };
  5. typedef struct CGPoint CGPoint;
  6.  
  7. /* Sizes. */
  8.  
  9. struct CGSize {
  10.   CGFloat width;
  11.   CGFloat height;
  12. };
  13. typedef struct CGSize CGSize;

Che, a loro volta ancora, contengono tipi CGFloat, ovvero tipi float. Se andiamo ad analizzare il codice della CGRectMake() troviamo:

Objective-C:
  1. CG_INLINE CGRect
  2. CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
  3. {
  4.   CGRect rect;
  5.   rect.origin.x = x; rect.origin.y = y;
  6.   rect.size.width = width; rect.size.height = height;
  7.   return rect;
  8. }

Ne deriva, quindi, che questa parte di codice:

Objective-C:
  1. UIButton *gbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  2. gbutton.frame = CGRectMake (12,409,100,40);
  3. [gbutton setTitle:@"Press" forState:UIControlStateNormal];
  4. [mainWindow addSubview:gbutton];

Potrebbe, a ragione, essere scritta anche come:

Objective-C:
  1. UIButton *gbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  2. gbutton.frame = (CGRect) {12,409,100,40};
  3. [gbutton setTitle:@"Press" forState:UIControlStateNormal];
  4. [mainWindow addSubview:gbutton];

Giusto per velocizzare un po' l'esecuzione del codice... :)

Post correlati

Questo articolo ti è stato utile?: Per nientePocoAbbastanzaMoltoMoltissimo
Loading ... Loading ...

2 commenti a: “Objective-C: un’alternativa all’uso di CGRectMake”

  1. 27 lug, 2009 Cristian:

    Curiosita': se si volesse imparare l'Obj-C, diciamo, da zero o quasi, a quali pubblicazioni ci si puo' rivolgere?

  2. 01 ago, 2009 Giovambattista Fazioli:

    @Cristian: cerca su Google Book (Google Libri) ci sono molte risorse (in inglese) quasi complete.

Lascia un commento

TAG XHTML PERMESSI: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERIMENTO CODICE:
<pre></pre>         // blocco generico
[code][/code]       // blocco generico
[as][/as]           // Actionscript
[css][/css]         // CSS Style Sheet
[html][/html]       // HTML
[js][/js]           // Javascript
[objc][/objc]       // Objective-C
[php][/php]         // PHP
[sql][/sql]         // SQL