xyk blog

最近は iOS 開発の記事が多めです。

View の Auto Layout によるアニメーションを無効にする

環境: Swift3

あるViewのSubviewのレイアウトをAuto Layoutで行った時にアニメーションしながら配置された。
この時のアニメーションは不要なので無効にする。
やり方はSubviewの配置が行われるlayoutSubviewsメソッドをオーバーライドして以下のようにアニメーションしないようにする。

方法1

UIView クラスメソッドのperform​Without​Animation:​のブロック内で実行させる。

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

方法2

CATransaction.setDisableActions(true)を実行後にlayoutSubviewsを実行させる。

override func layoutSubviews() {
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    super.layoutSubviews()
    CATransaction.commit()
}