gpt4 book ai didi

swift - 添加约束困惑 View

转载 作者:行者123 更新时间:2023-11-30 11:11:51 24 4
gpt4 key购买 nike

我有一个带有 UICollectionViewUISegmentedControl 的 View 。

我想更改约束,以便段 Controller 不会与 Collection View 重叠,如下图所示:

enter image description here

这是我的代码:

override func viewDidLoad()
{
super.viewDidLoad()

self.navigationItem.leftBarButtonItem = nil
self.tabBarController?.tabBar.isHidden = true


self.SegmentController.setTitle(SegmentAtext, forSegmentAt: 0)
self.SegmentController.setTitle(SegmentBtext, forSegmentAt: 1)


self.view.bringSubview(toFront: SegmentController)

self.LoadProducts(productsToShow: SegmentAtype)
}

所以我添加这个命令:

self.ProductsCollection.topAnchor.constraint(equalTo: SegmentController.bottomAnchor, constant: 10).isActive = true

但结果更糟:

enter image description here

现在段 Controller 几乎完全隐藏了!

如何解决这个问题?

编辑:

我的viewDidLayoutSubviews函数:

override func viewDidLayoutSubviews()
{
ProductsCollection.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
let bottomConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -50) //leaving space for search field
let leadingConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)

self.view.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
}

注意:

我的viewDidLayoutSubviews是在 super View 中实现的,它不包含UISegmentedControlUISegmentedControl 包含在继承 View 中。

编辑:更新的 View

enter image description here

最佳答案

如果您希望 UISegmentedControl 位于屏幕中央并在屏幕下方显示您的 Collection View

NSLayoutConstraint.activate([
segmentedControl.topAnchor.constraint(equalTo: view.topAnchor),
segmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor),
collectionView.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor),
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])

因此,我们在 View 顶部设置了分段控件,并将其居中,那么 Collection View 的顶部是分段控件的底部(如果需要,您可以添加一个常量用于填充),并且 View 的左右和底部

关于swift - 添加约束困惑 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com