UISegmentedControl隐藏在titleBar下

时间:2014-08-23 19:59:28

标签: ios swift uitabbarcontroller uisegmentedcontrol

我想我错过了UISegmentedControl和自动布局的东西。

我有一个TabbedApplication(UITabBarController),我创建了一个新的UIViewController作为标签。 在新视图中,我添加了UISegmentedControl,并使用自动布局将其置于顶部。

我想我完全不明白, 导致UISegmentedControl隐藏在titleBar下 。你能帮我理解我错过的东西吗? 谢谢。

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.
}
}

1 个答案:

答案 0 :(得分:1)

您的顶部空间垂直约束必须与您的顶部布局指南相关,而不是与您的容器边距相关。以下代码应解决此问题:

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))
}

请注意,水平约束设置也已被重写。