我想我错过了一些与UISegmentedControl和自动布局。
我有一个TabbedApplication (UITabBarController),我创建了一个新的UIViewController作为选项卡。在新视图中,我添加了UISegmentedControl,并使用自动布局将其放置在顶部。
我想我不完全明白一些事情,因为UISegmentedControl隐藏在titleBar下面。你能帮我理解我错过了什么吗?谢谢你。

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.
}
}发布于 2014-08-23 22:16:12
您的顶部空间垂直约束必须与您的顶部布局指南,而不是您的集装箱边缘。以下代码应修复此问题:
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))
}请注意,水平约束设置也已被重写。
https://stackoverflow.com/questions/25465856
复制相似问题