티스토리 뷰

iOS

collectionView 셀을 터치했을 때 효과 주기

꿀벌의달콤한여행 2021. 2. 26. 02:28

결과물

UICollectionView 를 사용하면서 사용자가 셀을 터치했을 때 간단한 애니메이션을 주고 싶었습니다. 그래서 여러 animate들을 적용해보던 중에 괜찮은 효과를 적용할 수 있어서 정리하였습니다.

적용한 코드

collectionView의 셀을 터치했을 때 사용자에게 터치 피드백을 주기위해서 사용하였다. CGAffineTransform(=아핀 변환)을 사용하여 셀의 크기를 살짝 줄였다 되돌렸고 이 때 스프링 효과를 주었다. 코드는 아래와 같다.

    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        if let cell = collectionView.cellForItem(at: indexPath) as? TaskTimerCell {
            let pressedDownTransform = CGAffineTransform(scaleX: 0.98, y: 0.98)
            UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 3, options: [.curveEaseInOut], animations: { cell.transform = pressedDownTransform })
        }
    }

    func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
        if let cell = collectionView.cellForItem(at: indexPath) as? TaskTimerCell {
            let originalTransform = CGAffineTransform(scaleX: 1, y: 1)
            UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 3, options: [.curveEaseInOut], animations: { cell.transform = originalTransform })
        }
    }

UIView.animate 로 스프링(=용수철) 효과 주기

class func animate(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions = [], animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)

인자정리

  1. duration: 애니메이션의 진행 시간. 여기 값은 초로 여겨진다. 0 이하의 값은 애니메이션이 없는 것으로 간주한다.

  2. delay: 애니메이션이 시작하기 전 기다리는 시간(역시 초로 값을 받음). 바로 애니메이션을 시작하려면 값을 0으로 하면 된다.

  3. dampingRatio: 1에 가까울수록 띠요옹 하는 진동이 줄어들고, 0에 가까울수록 진동이 증가된다

  4. velocity:

    The initial spring velocity. For smooth start to the animation, match this value to the view’s velocity as it was prior to attachment.
    (애니메이션의 부드러운 시작을 위해서는, velocity의 값을 기존에 뷰에 있던 속도값과 맞춰주는 것이 좋다)
    1의 값은 1초 동안 진행되는 전체 애니메이션의 거리와 동일하다. 예를 들어 전체 애니메이션의 거리가 200 포인트고 애니메이션 시작 속도를 100포인트/초 로 맞추고 싶다면 velocity 값을 0.5로 설정하면 된다.

  5. options: 애니메이션 수행을 위한 여러 옵션값을 배열 형태로 받는다. 반복여부나 되감기, 자연스러운 애니메이션을 위한 속도증감 여부, 기존 애니메이션 무시 여부(beginFromCurrentState), 유저 인터랙션 허용 여부 등의 옵션을 줄 수 있다. 종류는 UIView.AnimationOptions 에서 확인하자

  6. animations: 적용할 애니메이션이 담긴 블록. 이 블록 안에다 뷰의 프로퍼티들을 적어서(animatable한 애들만) 상태를 명시해주면 애니메이션을 적용시켜준다.

  7. completion: 애니메이션이 시퀸스가 끝난 후 실행되는 블록이다. 인자로 Bool 타입을 하나 받는다. 인자는 completion이 실행되기 전 애니메이션이 실제로 끝났는지 여부를 알려준다. duration을 0으로 설정하면 바로 다음 run loop cycle이 시작될 때 completion이 실행된다.

참고한 곳

Apple Developer Documentation
Animating UICollectionView or UITableView Cell Touches

댓글