操纵约束将视图移动到屏幕底部

时间:2017-12-17 16:21:21

标签: ios swift xcode nslayoutconstraint

我有一个在容器中水平和垂直对齐的集合视图。当用户选择我希望该集合视图移动到屏幕底部的单元格时,我希望UIView显示在集合视图的正上方。

以下是我的集合视图的约束方式。 constrains

所以我采用的方式是将底部空间约束作为我的代码文件中的插座。

@IBOutlet var collectionViewBottomConstraint: NSLayoutConstraint!

然后,当用户点击该单元格时,我在此处运行此功能

func showWatchView(selectedPath: Int) {
        UIView.animate(withDuration: 0.3, animations: {
            self.collectionViewBottomConstraint.constant = 0
        })
        clipsCollectionView.layoutIfNeeded()
}

然而,当我尝试这个时,它将集合视图移动到屏幕的顶部而不是屏幕的底部,它甚至没有动画它,它只是在那里。

1 个答案:

答案 0 :(得分:0)

常量需要设置为0

    class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var collectionViewOutlet: UICollectionView!
    @IBOutlet weak var bottomContraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionViewOutlet.delegate = self
        collectionViewOutlet.dataSource = self
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        showWatchView(selectedPath: indexPath.item)
    }

    func showWatchView(selectedPath: Int) {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
            self.bottomContraint.constant = 0
            self.view.layoutIfNeeded()
        }, completion: { (completed) in
            // do something
        })
    }

}

由于您希望collectionView位于底部,并且需要在您选择的持续时间内在动画内调用self.view.layoutIfNeeded(),因此初学者可以使用0.3。

相关问题