Auto Layout in Navigation Controller with UISegmen

2019-09-18 10:24发布

问题:

For a navigation controller I like to have a few controls placed in a view from top towards the bottom. I am using auto layout and added constraints, so that the views have a vertical gap to each other. This looks nice for iOS7 and iOS6 in a normal view controller, also for iOS7 in a navigation controller; but wrong in iOS6. The UISegmentedControl shows up wrong. See the screenshots.

It looks like the larger height of the UISegmentedControl is not taken into account for iOS6 view. Also it gets shifted out of place when switching from 3.5 inch to 4 inch screen.

Note that this only occurs in a navigation controller view. In the storyboard for the navigation controller I set Top Bar to "Opaque Navigation Bar". The upper button has a constraint "Top Space to Top Layout Guide". All other controls have a constraint "Top Space to ...." (control above them).

Are there any known fixes which I could apply?

What could be wrong? (I'm quite a newbie for auto layout.) Or is it just a bug which I have to work around somehow?


EDIT:

I tried placing the segmented control in an extra view, but that did not help either.

I could set a height constraint to the segmented control and that did help in a way. But this sets the same height to both iOS6 and iOS7 for the segmented control. My work around would now be to change/add the height constraint in code when the view loads and set a value depending on the iOS version. Are there other recommendations?


The screenshots:

In Navigation Controller, iOS6 view:

In Navigation Controller, iOS7 view:


In a "normal" view controller, iOS6 view:

In a "normal" view controller, iOS7 view:

回答1:

Select your button in interface builder, and in Attributes Inspector pane, set Type to Custom !



回答2:

My work around so far is to add a height constraint depending on the iOS version. In iOS6 the height of the segmented control is 43, in iOS7 the height is 28. The code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    int segCtrlHeight = (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) 
          ? 28 : 43;
    NSLayoutConstraint *lc = [NSLayoutConstraint constraintWithItem:self.segCtrl attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:segCtrlHeight];
    [self.view addConstraint:lc];
}

I'm answering my own question for now. I'd be glad if someone comes up with a better answer (preferably without having to add custom code).