连分数的SwiftUI递归视图

r1zhe5dt  于 2023-01-19  发布在  Swift
关注(0)|答案(1)|浏览(156)

我写了一个ContinuedFractionView来在我的(macos)应用程序上绘制连分数结构。
当我的CF列表相对较短时,它工作得很好。但是,当列表变长时(7,8,...),UI窗口几乎停止(几分钟没有响应)。
为什么?我怎样才能改善我的视野?

import SwiftUI

struct ContinuedFractionView: View {
    let continuedFraction: [Int]
    var body: some View {
        HStack(alignment: .top) {
            if continuedFraction.count > 1 {
                VStack {
                    Text("")
                    Text(String(continuedFraction[0]))
                }
                VStack {
                    Text("")
                    Text("+")
                }
                VStack {
                    Text("1")
                    Divider()
                        .background(Color.black)
                    ContinuedFractionView(continuedFraction:  Array(continuedFraction[1...]))
                }
            } else {
                Text(String(continuedFraction[0]))

            }
        }
    }
}

struct ContinuedFractionView_Previews: PreviewProvider {
    static var previews: some View {
        ContinuedFractionView(continuedFraction: [1,2,3,4,5,6,7])
    }
}
b5lpy0ml

b5lpy0ml1#

必须递归地完成吗?如果不是,应该很直接地画出:

struct ContentView: View {
    
    let fracs = [1,2,3,4,5]
    
    var body: some View {
        List {
            Section("Mine") {
                NonRecursive(fracs: fracs)
            }
            
            Section("Yours") {
                ContinuedFractionView(continuedFraction: fracs)
            }
        }
        .listStyle(.plain)
    }
}

struct NonRecursive: View {
    
    let fracs: [Int]

    var body: some View {
        VStack(alignment: .leading) {
            ForEach(Array(fracs.dropLast().enumerated()), id: \.1) { (index, frac) in
                HStack(alignment: .top) {
                    HStack {
                        Spacer(minLength: 0)
                        VStack(alignment: .trailing) {
                            Text("")
                            Text(frac, format: .number) + Text(" +")
                        }
                    }
                    .frame(width: CGFloat(index + 1) * 25)
                    VStack {
                        Text("1")
                        Divider()
                            .background(Color.black)
                        if let last = fracs.last, index == fracs.count - 2 {
                            Text(last, format: .number)
                        }
                    }
                }
            }
        }
    }
}

相关问题