UIVIew from XIB with Autolayout to UItableView Header

837 views Asked by At

I am writing because I have a problem with the Auto Layout. I'm trying to create a simple view in InterfaceBuilder with Auto Layout I want to load code and enter as a header of a table (not as header section). I explain briefly what are the characteristics. The imageView must be square and must be as wide as the screen. The space under the picture to the bottom of view that contains the button and label must be high 50 points. Between image and button has to be a fixed distance of 12 points. Between image and label must be a fixed distance of 13 points.

All these features are able to get them with Auto Layout. I added a constraint to the aspect ratio of the image (1: 1) and the various constraints for distances. all right.

The real problem is that by launching the app on iphone 6+ simulator (414 points of width), the image (with the label and button) goes above the cells.

Enabling various transparencies I noticed that the superView of Image View, only increase the width. It does not increase its height! How do I fix?

This is the code:

- (void)viewDidLoad{
//...    
PhotoDetailsHeaderView *hView = (PhotoDetailsHeaderView *)[[[NSBundle mainBundle] loadNibNamed:@"PhotoDetailsHeaderView" owner:self options:nil] objectAtIndex:0];
    hView.delegate = self;
    
    self.tableView.tableHeaderView = hView;
//...
}

This is how I create the xib: Interface builder xib creation

and this is how it is on the simulator, the green box is Uiimageview and the yellow box (under green box) is the mainview (or superview):

enter image description here

How can fix it?

Many thanks to all!

2

There are 2 answers

0
morgan1189 On

The problem is probably that in iOS you have to reset the header of the table view manually (if it has changed its size). Try something along these lines:

CGRect newFrame = imageView.frame;
imageView.size.height = imageView.size.width;
imageView.frame = newFrame;
[self.tableView setTableHeaderView:imageView];

This code should be in -(void)viewDidLayoutSubviews method of your view controller.

4
johnpatrickmorgan On

You'll need to add a property to store your PhotoDetailsHeaderView:

@property (nonatomic, strong) PhotoDetailsHeaderView *headerView;

Then calculate its expected frame in viewDidLayoutSubviews. If it needs updating, update its frame and re-set the tableHeaderView property. This last step will force the tableView to adapt to the header's updated frame.

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];

    CGRect expectedFrame = CGRectMake(0.0,0.0,self.tableview.size.width,self.tableView.size.width + 50.0);

    if (!CGRectEqualToRect(self.headerView.frame, expectedFrame)) {
        self.headerView.frame = expectedFrame;
        self.tableView.tableHeaderView = self.headerView;
    }
}