【问题标题】:UISegmentedControl is hidden under the titleBarUISegmentedControl 隐藏在 titleBar 下
【发布时间】:2014-10-17 10:04:33
【问题描述】:

我想我在 UISegmentedControl 和自动布局方面遗漏了一些东西。

i have a TabbedApplication (UITabBarController), and i created a new UIViewController to act as tab. 在新视图中我添加了 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.
}
}

【问题讨论】:

标签: ios swift uitabbarcontroller uisegmentedcontrol


【解决方案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))
}

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

【讨论】:

  • 谢谢 :) 我是 swift 和 UIKit 的新手,我有很多东西要学,你能推荐我一个可以帮助我更好地理解 UIKit 的教程吗,谢谢。
猜你喜欢
  • 2012-07-05
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多