code

Swift의 블록 (animateWithDuration : animations : completion :)

codestyles 2020. 8. 17. 08:57
반응형

Swift의 블록 (animateWithDuration : animations : completion :)


Swift에서 블록을 작동시키는 데 문제가 있습니다. 다음은 완료 블록없이 작동 한 예입니다.

UIView.animateWithDuration(0.07) {
    self.someButton.alpha = 1
}

또는 후행 폐쇄없이 :

UIView.animateWithDuration(0.2, animations: {
    self.someButton.alpha = 1
})

하지만 완료 블록을 추가하려고하면 작동하지 않습니다.

UIView.animateWithDuration(0.2, animations: {
    self.blurBg.alpha = 1
}, completion: {
    self.blurBg.hidden = true
})

자동 완성 기능이 제공 completion: ((Bool) -> Void)?되지만 작동 방법을 알 수 없습니다. 또한 후행 폐쇄로 시도했지만 동일한 오류가 발생했습니다.

! Could not find an overload for 'animateWithDuration that accepts the supplied arguments

Swift 3/4 업데이트 :

// This is how I do regular animation blocks
UIView.animate(withDuration: 0.2) {
    <#code#>
}

// Or with a completion block
UIView.animate(withDuration: 0.2, animations: {
    <#code#>
}, completion: { _ in
    <#code#>
})

명확성이 부족하다고 생각하기 때문에 완료 블록에 후행 폐쇄를 사용하지 않지만 마음에 들면 아래 Trevor의 답변을 볼 수 있습니다 .


animateWithDuration의 완료 매개 변수는 하나의 부울 매개 변수를 취하는 블록을 사용합니다. Obj C 블록에서와 같이 신속하게 클로저가 취하는 매개 변수를 지정해야합니다.

UIView.animateWithDuration(0.2, animations: {
    self.blurBg.alpha = 1
}, completion: {
    (value: Bool) in
    self.blurBg.hidden = true
})

여기서 중요한 부분은 (value: Bool) in. 이는 컴파일러에게이 클로저가 'value'레이블이 붙은 Bool을 취하고 void를 반환 함을 알려줍니다.

참고로 bool을 반환하는 클로저를 작성하려면 구문은 다음과 같습니다.

{(value: Bool) -> bool in
    //your stuff
}

완료가 정확합니다. 클로저는 Bool매개 변수 를 허용해야합니다 : (Bool) -> (). 시험

UIView.animate(withDuration: 0.2, animations: {
    self.blurBg.alpha = 1
}, completion: { finished in
    self.blurBg.hidden = true
})

in키워드 와 함께 밑줄 은 입력을 무시합니다.

UIView.animateWithDuration(0.2, animations: {
    self.blurBg.alpha = 1
}, completion: { _ in
    self.blurBg.hidden = true
})

위의 답변을 기반으로 한 내 솔루션이 있습니다. 뷰를 페이드 아웃하고 거의 보이지 않게 숨 깁니다.

스위프트 2

func animateOut(view:UIView) {

    UIView.animateWithDuration (0.25, delay: 0.0, options: UIViewAnimationOptions.CurveLinear ,animations: {
        view.layer.opacity = 0.1
        }, completion: { _ in
            view.hidden = true
    })   
}

스위프트 3, 4, 5

func animateOut(view: UIView) {

    UIView.animate(withDuration: 0.25, delay: 0.0, options: UIView.AnimationOptions.curveLinear ,animations: {
        view.layer.opacity = 0.1
    }, completion: { _ in
        view.isHidden = true
    })
}

자, 이것은 컴파일됩니다.

스위프트 2

UIView.animateWithDuration(0.3, animations: {
    self.blurBg.alpha = 1
}, completion: {(_) -> Void in
    self.blurBg.hidden = true
})

스위프트 3, 4, 5

UIView.animate(withDuration: 0.3, animations: {
    self.blurBg.alpha = 1
}, completion: {(_) -> Void in
    self.blurBg.isHidden = true
})

내가 Bool 영역을 밑줄로 만든 이유는 해당 값을 사용하지 않기 때문입니다. 필요한 경우 (_)를 (value : Bool)으로 바꿀 수 있습니다.


때로는 상황에 따라 다른 방식으로 애니메이션을 적용하기 위해 이것을 변수에 던지고 싶을 때가 있습니다. 그것을 위해 당신이 필요합니다

 let completionBlock : (Bool) -> () = { _ in 
 }

Or you could use the equally verbose:

 let completionBlock = { (_:Bool) in 
 }

But in any case, you have have to indicate the Bool somewhere.


SWIFT 3.x + 4.x

I'd like to make an update and simplify the things.

Example below is implemented in any view it is hiding slowly and when it is completely transparent; removes it self from parent view

ok variable will always returns true with animation termination.

    alpha = 1
    UIView.animate(withDuration: 0.5, animations: {
        self.alpha = 0
    }) { (ok) in
        print("Ended \(ok)")
        self.removeFromSuperview()
    }

참고URL : https://stackoverflow.com/questions/24071334/blocks-on-swift-animatewithdurationanimationscompletion

반응형