UIView Programmatic Width Constraint

133 views Asked by At

What kind of constraint(s) do I need to add in order to ensure when the phone rotates the search bar and label span the width of the phone?

Below is code I am using to spin up a search bar & label and add them to a table header:

self.venueSearchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.venueSearchController.searchResultsUpdater = self;
self.venueSearchController.searchBar.delegate = self;
self.venueSearchController.delegate = self;
self.venueSearchController.dimsBackgroundDuringPresentation = NO;
self.venueSearchController.hidesNavigationBarDuringPresentation = YES;
self.venueSearchController.searchBar.frame = CGRectMake(0, 0, self.venueSearchController.view.frame.size.width, 44.0);

// create a UISegmentControl
UILabel *tableHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.venueSearchController.view.frame.size.width, 30)];
[tableHeaderLabel setTextAlignment:NSTextAlignmentCenter];
tableHeaderLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:18];
tableHeaderLabel.text = @"Text Here";
tableHeaderLabel.backgroundColor = [UIColor redColor];

// create a custom UIView

CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, applicationFrame.size.width, 74)];

[myView addSubview:tableHeaderLabel]; // add header label
[myView addSubview:self.venueSearchController.searchBar]; // add search bar to custom view

self.tableView.tableHeaderView = myView;
1

There are 1 answers

1
aherrick On

FYI I fixed this by simply using autoresizingMask

tableHeaderLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

self.venueSearchController.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;