2

I'm working right now at a complex user interface for a game which contains both IB elements and programmatic created elements. My question is about the best practices to be used when creating an interface: i know that i should avoid hard-coding values for the frame of the views but also if i let the app calculate the frames after the screen size the results are not as good as i would hope.

Now i am using a combination of hardcoding and self calculating:

    backQuestion = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 760, 400)];
    backQuestion.center = CGPointMake(self.view.bounds.size.height/2, self.view.bounds.size.width/2);
    questionLabel = [[UILabel alloc]initWithFrame:CGRectMake(backQuestion.frame.origin.x+backQuestion.frame.size.width*0.05, backQuestion.frame.origin.y+backQuestion.frame.size.width*0.02, backQuestion.frame.size.width*0.9, backQuestion.frame.size.height*0.35)];

What are the more experienced developers using when creating interfaces ? Is there any good article i should read ?

Macaret
  • 797
  • 9
  • 33

2 Answers2

0

As often as I can I prefer to use Interface Builder to build interfaces. This allows me to draw the interface and see potential problems in a variety of size and orientations. It also allows me to quickly design the auto-layout properties. While this can be done in code is it very time consuming and creates code that is not very DRY.

Kyle
  • 1,662
  • 2
  • 21
  • 38
0

Whenever possible I try to tie the positions in the code to positions set in IB.

For example, just because an element needs to be resized programmatically, doesn't mean you can't derive its initial position from IB and then apply a relative offset in code.

You could also add hidden views in IB that exist purely for spacing purposes (hidden views have almost no runtime overhead). You can then access them in viewDidLoad and store their positions to use in layout calculations.

Also, consider using nested views + autoresizing to control layout instead of code. For example, if you need to divide your content into two columns, you can divide the main view into two transparent views that each autoresize to fit half the screen, then place your content inside them. By nesting transparent views like this you can create more or less any kind of grid without resorting to code.

Finally, for problems like top-aligned UILabels, or views that need to resize themselves based on their content, consider creating "smart" view subclasses that resize or reposition themselves automatically relative to their siblings. For example, you could have a "StackLabel" that automatically sets its own height by calling [self sizetoFit] and then positions itself below the previous label it finds within its superview. Using smart views avoids the need for putting repetitive layout code in your controller.

(Or you could bite the bullet and learn AutoLayout of course.)

Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103