本文介绍了SwiftUI 自定义视图永远重复动画显示为意外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义 LoadingView 作为从 Internet 加载对象的指示器.添加到NavigationView时,显示如下在此处输入图片描述

I created a custom LoadingView as a Indicator for loading objects from internet. When add it to NavigationView, it shows like thisenter image description here

我只希望它显示在屏幕中间而不是从左上角移动

I only want it showing in the middle of screen rather than move from top left corner

这是我的代码

struct LoadingView: View {
    @State private var isLoading = false
    var body: some View {
        Circle()
            .trim(from: 0, to: 0.8)
            .stroke(Color.primaryDota, lineWidth: 5)
            .frame(width: 30, height: 30)
            .rotationEffect(Angle(degrees: isLoading ? 360 : 0))
            .onAppear {
                withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) {
                    self.isLoading.toggle()
                }
            }
            
    }
}

和我的内容视图

struct ContentView: View {
    var body: some View {
        NavigationView {
            LoadingView()
                .frame(width: 30, height: 30)
        }
    }
}

推荐答案

这是 NavigationView 的一个错误,我试图杀死所有可能的动画但 NavigationView 忽略了我所有的试试,NavigationView 给孩子添加一个内部动画!我们现在能做的就在这里!

This is a bug from NavigationView, I tried to kill all possible animation but NavigationView ignored all my try, NavigationView add an internal animation to children! here all we can do right now!

struct ContentView: View {
    var body: some View {
        NavigationView {
            LoadingView()
        }
        
    }
}


struct LoadingView: View {
    
    @State private var isLoading: Bool = Bool()
    
    var body: some View {
        
        Circle()
            .trim(from: 0, to: 0.8)
            .stroke(Color.blue, lineWidth: 5.0)
            .frame(width: 30, height: 30)
            .rotationEffect(Angle(degrees: isLoading ? 360 : 0))
            .animation(Animation.linear(duration: 1).repeatForever(autoreverses: false), value: isLoading)
            .onAppear { DispatchQueue.main.async { isLoading.toggle() } }
 
    }
    
}

这篇关于SwiftUI 自定义视图永远重复动画显示为意外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 11:17