使用UICollectionView自定义发送消息动画,如iMessage发送消息

时间:2017-12-25 07:41:37

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewflowlayout

我正在开发聊天应用程序。我正在使用UIcollectionview来显示消息。我正在尝试在发送按钮上创建动画。当用户点击发送UIButton时,我需要像iMessage这样的动画。 为了创建这样的动画,我使用两种不同的方式但没有获得适当的动画 我创建了一个演示。在那个演示中,我实现了不同的方法。

演示链接:
https://www.dropbox.com/s/z8rxjkpuxzs95kp/AdvanceCollection.zip?dl=0

下面是我需要的动画: https://www.dropbox.com/s/yo35lsm7yrc2oqu/Screen%20Recording.mov?dl=0

我应用了2种方法。以下是方法说明。

第一种方法: 在第一种方法中,我自定义了 FlowLayout 。我知道这是正确的方法,但没有得到正确的曲线动画。

override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            guard let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath),
            let added = addedItem,
                added == itemIndexPath else {
                    return nil
            }
            // set new attributes

            attributes.frame = CGRect(x: 0, y: 0, width: 500, height: 500)
            //attributes.center = CGPoint(x: self.collectionView!.frame.width - 23.5, y: -24.5)
            attributes.center = CGPoint(x: 0.0, y: 100.0)

            attributes.alpha = 1.0

            attributes.transform = CGAffineTransform(scaleX: 0.15, y: 0.15)

            attributes.zIndex = 20

            return attributes
        }

第二种方法:在第二种方法中,我使用willdisplaycell方法实现动画。根据我的观点,我知道这不是自定义布局的正确方法,但我尝试过。在第二种方法中,我从底部获得动画,但 x y 宽度高度。此外,任何可见的动画也与 iMessage发送消息动画

不同
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if !self.collectionData[indexPath.row].isAnimated
        {
            cell.frame =  CGRect(x: 0, y: chatView.frame.origin.y, width: 1000.0, height: chatView.frame.size.height)
            UIView.animate(withDuration: 10.0, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.curveEaseIn, animations: {
                cell.frame = CGRect(x:0, y:  cell.frame.origin.y, width: cell.frame.size.width, height: cell.frame.size.height)
            }, completion: { finished in
               self.collectionData[indexPath.row].isAnimated = true
            })
        }
    }

1 个答案:

答案 0 :(得分:1)

编辑:请参阅此处的tableView演示animateCell

我认为您可以尝试使用tableView而不是collectionView来实现这一点,因为collectionView布局非常愚蠢

我假设您已经为collectionView创建了一个自定义xib单元格,然后执行此操作

1-将top,bottom,leading,trailing约束正确设置到消息标签的超级视图

2-将消息标签的顶部约束更改为400

3-设置勾选顶部约束为 IBOutlet

4- cellForRowAt 将该约束设置为20

5-然后做那样的动画

  UIView.animateWithDuration(1.0,
 {
    cell.layoutSubview()

    cell.layoutIfNeeded()

 }

注意: collectionView的问题是chagning item的大小,因此动画可以发生,上面的解决方案与tableView完美配合