UICollectionView位置和分段控制编程错误

时间:2016-09-19 02:54:55

标签: ios swift ios9.3 programmatically

我想将我的collectionView放在我的Segmented Control下面,但是我不知道我的约束是否错误。我还想放置我的分段控件来填充整个框架宽度减去十,但是在集合视图上方居中。

这是我一直在尝试的代码:

    let item = ["Past", "Future"]
    let customSC = UISegmentedControl(items: item)

    customSC.selectedSegmentIndex = 0
    let frame = UIScreen.mainScreen().bounds
    customSC.frame = CGRectMake(0, 0,
                                frame.width, 25)

    customSC.layer.cornerRadius = 5.0  // Don't let background bleed
    customSC.backgroundColor = MaterialColor.white
    customSC.tintColor = MaterialColor.red.accent3

    customSC.translatesAutoresizingMaskIntoConstraints = false
    //customSC.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
    //collectionView?.translatesAutoresizingMaskIntoConstraints = false
    collectionView?.addSubview(customSC)
    customSC.centerXAnchor.constraintEqualToAnchor(collectionView?.centerXAnchor).active = true
    //collectionView?.topAnchor.constraintEqualToAnchor(customSC.bottomAnchor,constant: 2).active = true

这是我输出的图像。我将我的分段视图作为我的第一个视图来填充整个宽度框架和我的集合视图以显示在我的Segmented控件下面。

enter image description here

感谢。

1 个答案:

答案 0 :(得分:0)

您需要在当前View上添加CustomSc而不是Collection视图。如此

    self.view.addSubview(customSC)

像这样设置CollectionView框架

    collectionView.frame = CGRectMake(0, customSC.frame.origin.y + 25, self.view.frame.size.width, set Acc. to your req.)

现在在当前视图中添加Collectionview,如下所示

    self.view.addSubview(collectionView)