迅速:带有按钮的动画

时间:2018-08-08 17:51:04

标签: ios swift uibutton uiviewanimation

我使用以下代码创建带有按钮的动画:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

    switch indexPath.section {
    case 0:
        self.button1.constant = self.button2.constant
    case 6:
        self.button3.constant = self.button4.constant
    default:
        self.button1.constant = 0
        self.button3.constant = 0
    }

    UIView.animate(withDuration: 1.0, delay: 0.0,
                   options: [], animations: {
                    self.view.layoutIfNeeded()
    })
}

我有collectionView。但是我的collectionView也用我的按钮动画了。我该怎么做只有按钮动画?

此代码无效:

UIView.animate(withDuration: 1.0, delay: 0.0,
               options: [], animations: {
                self.myButton.layoutIfNeeded()
                self.myButton1.layoutIfNeeded()
})

3 个答案:

答案 0 :(得分:1)

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

UIView.animate(withDuration: 1.0, delay: 0.0,
                       options: [], animations: {

        switch indexPath.section {
        case 0:
            self.button1.constant = self.button2.constant
            self.myButton1.layoutIfNeeded()
        case 6:
            self.button3.constant = self.button4.constant
            self.myButton3.layoutIfNeeded()
        default:
            self.button1.constant = 0
            self.button3.constant = 0

            self.myButton1.layoutIfNeeded()
            self.myButton6.layoutIfNeeded()
        }

    })
}

答案 1 :(得分:0)

尝试继承UICollectionView并重写layoutSubviews方法,如下所示:

override func layoutSubviews() {
     UIView.performWithoutAnimation {
         super.layoutSubviews()
     }
}

希望这会有所帮助。

答案 2 :(得分:0)

我确认此代码有效。

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    guard let cell = cell as? MyCollectionViewCell else { return }

    cell.yourConstraint.constant = 10 //desired value

    UIView.animate(withDuration: 0.3) {
        cell.layoutIfNeeded()
    }
}

我认为您的问题是,名为“ button1”,“ button2”等的约束都钩接到了视图控制器的视图或collectionView上。

您必须在按钮(可能在集合视图单元格内部)和集合视图单元格的contentView之间设置约束,并在自定义UICollectionViewCell类中具有该约束属性。