shay te
shay te

Reputation: 1068

UISegmentedControl is hidden under the titleBar

i guess i am missing something with the UISegmentedControl and auto layout.

i have a TabbedApplication (UITabBarController), and i created a new UIViewController to act as tab. to the new view i added UISegmentedControl, and place it to top using auto layout.

i guess i don't understand completely something , cause the UISegmentedControl is hiding under the titleBar . can u help me understand what i am missing ? thank you .

segmentedControlHidder

import Foundation
import UIKit;

class ViewLikes:UIViewController {

override func viewDidLoad()  {
    super.viewDidLoad()
    title = "some title";


    var segmentControl:UISegmentedControl = UISegmentedControl(items:["blash", "blah blah"]);
    segmentControl.selectedSegmentIndex = 1;


    segmentControl.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addSubview(segmentControl)

    //Set layout
    var viewsDict = Dictionary <String, UIView>()
    viewsDict["segment"] = segmentControl;

    //controls
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segment]-|",
        options: NSLayoutFormatOptions.AlignAllCenterX,
        metrics: nil,
        views: viewsDict))

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[segment]",
        options: NSLayoutFormatOptions(0),
        metrics: nil,
        views: viewsDict))
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

Upvotes: 1

Views: 286

Answers (1)

Imanou Petit
Imanou Petit

Reputation: 92409

Your top space vertical constraint has to be related to your Top Layout Guide, not to your container margin. The following code should fix this problem:

override func viewDidLoad() {
    super.viewDidLoad()

    let segmentControl = UISegmentedControl(items:["blash", "blah blah"])
    segmentControl.selectedSegmentIndex = 1

    segmentControl.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addSubview(segmentControl)

    //Horizontal constraints
    view.addConstraint(NSLayoutConstraint(item: segmentControl, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))

    //Horizontal constraints
    let viewsDict = ["segment" : segmentControl]

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segment]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
}

Note that the horizontal constraints setting has also been rewritten.

Upvotes: 1

Related Questions