views:

352

answers:

2

Coming from a web background, where explicit sizing is generally not considered best practice, I am not used to 'hardcoding' positioning values.

For example, is it perfectly acceptable to create custom UITableViewCells with hardcoded values for subviews' frames and bounds? It seems that when the user rotates the device, I'd need another set of hardcoded frames/bounds? If Apple decides to release a larger TABLET ... then I'd need yet another update to the code - it sounds strange to me in that it doesn't seem to scale well.

In my specific case, I'd like to use a cell of style UITableViewCellStyleValue2 but I need a UITextField in place of the detailTextLabel. I hate to completely write my own UITableViewCell but it does appear that in most text input examples I've found, folks are creating their own cells and hardcoded sizing values.

If that is the case, is there any way I can adhere to the predefined positioning and sizing of the aforementioned style's textLabel and detailTextLabel (ie: I'd like to replace or overlay my UITextField in place of the detailTextLabel but yet have all subview positioning stay in tact)? Just after creating a default cell, cell.textLabel.frame is returning 0 so I assume it doesn't get sized until the cell's 'layoutSubviews' gets invoked .. and obviously that is too late for what I need to do.

Hope this question makes sense. I'm just looking for 'best practice' here.

-Luther

+1  A: 

There is no best practice. It depends on your application. You can use IB to do dynamic resizing with autorotation. And set properties to modify sizeOfFit, etc.

You can also set the frame of any view before layoutSubViews by creating a view and initializing it with CGRect.

There a lot of flexibility. I tend to do the static things in IB and the rest in code.

Jordan
A: 

Generally it's a bad idea to hardcode these values because the contents will move around depending on:

  • Whether there's an image in the cell
  • Edit mode
  • Delete mode
  • Move (rearrange) mode
  • What kind of accessoryView (if any) is showing
  • Rotation
  • Screen sizes
  • etc.

If you're using the default styles most of these will get taken care of but if you're using custom cells then you'll have to check for various modes and adjust position and size accordingly.

If you go that way, you'll want to override layoutSubviews in the UITableViewCell subclass. One approach is for each subview to have a {subView}Frame method that returns a CGRect. In each method you could test for the condition you're checking for and return a CGRect loaded with the right position (ideally, it'll be calculated proportionally instead of with absolutes).

Then your layoutSubviews would look something like this:

- (void)layoutSubviews {
    [super layoutSubviews];

    [subView1 setFrame:[self subView1Frame]];
    [subView2 setFrame:[self subView2Frame]];
    [subView3 setFrame:[self subView3Frame]];
    ...
}
Ramin