AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79596792
Accepted
User
User
Asked: 2025-04-28 23:18:20 +0800 CST2025-04-28 23:18:20 +0800 CST 2025-04-28 23:18:20 +0800 CST

Como corrigir a mesclagem de animações?

  • 772

Tenho um código que rola imagens em tela cheia para frente e para trás ao tocar no lado esquerdo ou direito da tela. Quando uma imagem aparece na tela, ela executa um dos seguintes tipos de animação: superior, inferior, esquerda, direita, zoom in, zoom out — cada uma dessas animações consiste em duas subanimações (a primeira animação é rápida e a segunda é em loop).

O problema é que, às vezes, ao alternar imagens, as coordenadas da animação se acumulam. Em circunstâncias normais, as animações deveriam afetar apenas X, Y ou Escala. Mas, no meu caso, às vezes acontece que as imagens se movem na diagonal (X + Y), a animação ultrapassa os limites da imagem e vejo áreas pretas na tela. Isso não deveria acontecer. Como posso corrigir isso?

Estou usando removeAllAnimationsantes de cada animação, mas não ajuda.

código completo:

class ReaderController: UIViewController, CAAnimationDelegate {
    
    var pagesData = [PageData]()
    var index = Int()
    var pageIndex: Int = -1
    
    let pageContainer: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    let pageViews: [PageLayout] = {
        let view = [PageLayout(), PageLayout()]
        view[0].translatesAutoresizingMaskIntoConstraints = false
        view[1].translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private weak var currentTransitionView: PageLayout?
        
    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupConstraints()

        pageViews[0].index = index
        pageViews[1].index = index
        pageViews[0].pageIndex = pageIndex
        pageViews[1].pageIndex = pageIndex
        
        pageTransition(animated: false, direction: "fromRight")
    }
        
    func setupViews() {
        pageContainer.addSubview(pageViews[0])
        pageContainer.addSubview(pageViews[1])
        view.addSubview(pageContainer)
    }
        
    func setupConstraints() {
        pageContainer.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
        pageContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
        pageContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
        pageContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true

        pageViews[0].topAnchor.constraint(equalTo: pageContainer.topAnchor).isActive = true
        pageViews[0].bottomAnchor.constraint(equalTo: pageContainer.bottomAnchor).isActive = true
        pageViews[0].leadingAnchor.constraint(equalTo: pageContainer.leadingAnchor).isActive = true
        pageViews[0].trailingAnchor.constraint(equalTo: pageContainer.trailingAnchor).isActive = true

        pageViews[1].topAnchor.constraint(equalTo: pageContainer.topAnchor).isActive = true
        pageViews[1].bottomAnchor.constraint(equalTo: pageContainer.bottomAnchor).isActive = true
        pageViews[1].leadingAnchor.constraint(equalTo: pageContainer.leadingAnchor).isActive = true
        pageViews[1].trailingAnchor.constraint(equalTo: pageContainer.trailingAnchor).isActive = true
    }
        
    func loadData(fileName: Any) -> PagesData {
        var url = NSURL()
        url = Bundle.main.url(forResource: "text", withExtension: "json")! as NSURL
        let data = try! Data(contentsOf: url as URL)
        let person = try! JSONDecoder().decode(PagesData.self, from: data)
        return person
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: view.self)

            if view.safeAreaInsets.left > 30 {
                if (location.x > self.view.frame.size.width - (view.safeAreaInsets.left * 1.5)) {
                    pageTransition(animated: true, direction: "fromRight")
                } else if (location.x < (view.safeAreaInsets.left * 1.5)) {
                    pageTransition(animated: true, direction: "fromLeft")
                }
            }

            else {
                if (location.x > self.view.frame.size.width - 40) {
                    pageTransition(animated: true, direction: "fromRight")
                } else if (location.x < 40) {
                    pageTransition(animated: true, direction: "fromLeft")
                }
            }
        }
        
    }
    
    func pageTransition(animated: Bool, direction: String) {
        let result = loadData(fileName: pagesData)
        
        switch direction {
        case "fromRight":
            pageIndex += 1
        case "fromLeft":
            pageIndex -= 1
        default: break
        }
        
        pageViews[0].pageIndex = pageIndex
        pageViews[1].pageIndex = pageIndex
        
        guard pageIndex >= 0 && pageIndex < result.pagesData.count else {
            pageIndex = max(0, min(pageIndex, result.pagesData.count - 1))
            return
        }
        
        let fromView = pageViews[0].isHidden ? pageViews[1] : pageViews[0]
        let toView = pageViews[0].isHidden ? pageViews[0] : pageViews[1]
        toView.imageView.layer.removeAllAnimations()
        toView.imageView.transform = .identity
        toView.configure(theData: result.pagesData[pageIndex])
        if animated {
            fromView.isHidden = true
            toView.isHidden = false
        } else {
            fromView.isHidden = true
            toView.isHidden = false
        }
    }
    
}

class PageLayout: UIView {
            
    var index = Int()
    var pageIndex = Int()
    
    let imageView: UIImageView = {
        let image = UIImageView()
        image.contentMode = .scaleAspectFill
        image.translatesAutoresizingMaskIntoConstraints = false
        return image
    }()

    var imageViewTopConstraint = NSLayoutConstraint()
    var imageViewBottomConstraint = NSLayoutConstraint()
    var imageViewLeadingConstraint = NSLayoutConstraint()
    var imageViewTrailingConstraint = NSLayoutConstraint()
    
    var imagePosition = ""
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(imageView)
        setupConstraints()
    }
    
    func setupConstraints() {
        
        imageView.layer.removeAllAnimations()
        imageView.transform = .identity
        
        removeConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint,
                           imageViewTrailingConstraint])
        
        switch imagePosition {
            
        case "top":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: -40.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: 0, y: 40.0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 0, y: -40.0)
                }, completion: nil)
            })
            
        case "bottom":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 40.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: 0, y: -40)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 0, y: 40)
                }, completion: nil)
            })
            
        case "left":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: -40.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: 40, y: 0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: -40, y: 0)
                }, completion: nil)
            })
            
        case "right":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 40.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: -40, y: 0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 40, y: 0)
                }, completion: nil)
            })
            
        case "zoomin":
            
            imageView.transform = CGAffineTransformScale(.identity, 1.0, 1.0)
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = .identity
                }, completion: nil)
            })
            
        case "zoomout":
            
            imageView.transform = CGAffineTransformScale(.identity, 1.1, 1.1)
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.scaledBy(x: 1.1, y: 1.1)
                }, completion: nil)
            })
            
        default:
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
        }
    }
        
    func configure(theData: PageData) {
        imageView.image = UIImage(named: "page\(pageIndex+1)")
        imagePosition = theData.imagePosition
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("Not happening")
    }
    
}

struct PagesData: Decodable {
    var pagesData: [PageData]
}

struct PageData: Decodable {
    let textData, textPosition, textColor, shadowColor, textAlignment, imagePosition: String
}

JSON:

{
    "pagesData" : [
        
        {
            "textData" : "",
            "textPosition" : "topLeft",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "left",
        },
        
        {
            "textData" : "",
            "textPosition" : "bottomLeft",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "bottom",
        },
        
        {
            "textData" : "",
            "textPosition" : "zoomin",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "right",
        },
        
        {
            "textData" : "",
            "textPosition" : "bottomCenter",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "zoomout",
        },
        
        {
            "textData" : "",
            "textPosition" : "topLeft",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "left",
        },
        
    ]
}
  • 1 1 respostas
  • 37 Views

1 respostas

  • Voted
  1. Best Answer
    DonMag
    2025-04-29T04:31:09+08:002025-04-29T04:31:09+08:00

    Não consigo reproduzir suas "imagens se movem diagonalmente (X + Y)" ... embora ao tocar rapidamente eu veja "a animação ultrapassa os limites da imagem" .

    O que pode corrigir o problema é NÃO executar a segunda parte da animação se a primeira parte não tiver sido concluída.

    Tente alterar seus blocos de animação para isto:

        UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
            self.imageView.transform = CGAffineTransform(translationX: 0, y: 40.0)
        }, completion: { bCompleted in
            if bCompleted {
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 0, y: -40.0)
                }, completion: nil)
            }
        })
    
    • 1

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve