Ios SwuftUI性能非常差,有许多矩形需要着色

Ios SwuftUI性能非常差,有许多矩形需要着色,ios,swift,iphone,swiftui,Ios,Swift,Iphone,Swiftui,我创建了一个类似像素的矩形网格。为了在填充期间执行simil动画,我想延迟部分或全部着色,但性能非常差,我认为每次更新都会刷新所有矩形 行为 代码 struct Pixel: Identifiable, Hashable { var id: Int var isColored: Bool } class Model: ObservableObject { @Published var pixels: [Pixel] init(totalP

我创建了一个类似像素的矩形网格。为了在填充期间执行simil动画,我想延迟部分或全部着色,但性能非常差,我认为每次更新都会刷新所有矩形

行为

代码

struct Pixel: Identifiable, Hashable {
    var id: Int
    var isColored: Bool
}


class Model: ObservableObject {
    
    @Published var pixels: [Pixel]
    
    init(totalPixels: Int) {
        pixels = (1...totalPixels).map{ Pixel(id: $0, isColored: false)}
    }
    
    func pixelsRange(num:Int, clusterDimension:Int) -> [Pixel]{
        return Array(pixels[(num-1)*clusterDimension..<clusterDimension*num])
    }

    func startFillingAllAnimated() {
        for idx in pixels.indices {
            let addTime = idx
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(addTime) * 0.1) {
                self.pixels[idx].isColored = true
            }
        }
    }
}
struct TotalView: View {
    
    static var totalPixels = 1280
    
    @StateObject var model = Model(totalPixels: totalPixels)
    
    var clusterDimension = 16
    
    static let bigSpacing:CGFloat = 2
    
    let bigColumns = [
        GridItem(.flexible(), spacing: bigSpacing),
        GridItem(.flexible(), spacing: bigSpacing),
        GridItem(.flexible(), spacing: bigSpacing),
        GridItem(.flexible(), spacing: bigSpacing),
        GridItem(.flexible(), spacing: bigSpacing),
        GridItem(.flexible(), spacing: bigSpacing),
        GridItem(.flexible(), spacing: bigSpacing),
        
        GridItem(.flexible(), spacing: bigSpacing)
    ]
    
    @State var numToBeColored: Int = 8
    
    var body: some View {
        
        VStack {

            Button("start") {
                model.startFillingAllAnimated()
            }
            ScrollView {
                LazyVGrid(columns: bigColumns, alignment: .center, spacing: 2){
                    ForEach(0..<TotalView.totalPixels/clusterDimension, id: \.self) { num in
                        ClusterView(pixels: $model.pixels, clusterNumber: num, clusterDimension: clusterDimension, color: .red)
                    }
                }
            }
            .padding(.horizontal, 4)
        }
        
    }
}





struct ClusterView: View {
    
    
    @Binding var pixels: [Pixel]
    let clusterNumber: Int
    let clusterDimension: Int
    let color: Color
    
    static let spacing:CGFloat = 2
    static let boxDimension:CGFloat = 9

    let columns = [
        GridItem(.fixed(boxDimension), spacing: spacing),
        GridItem(.fixed(boxDimension), spacing: spacing),
        GridItem(.fixed(boxDimension), spacing: spacing),
        GridItem(.fixed(boxDimension), spacing: spacing)
    ]

    var body: some View {
  
        LazyVGrid(columns: columns, alignment: .center, spacing: ClusterView.spacing) {
            ForEach(pixels[clusterNumber*clusterDimension..<clusterDimension*(clusterNumber+1)], id: \.self) { pixel in
                Rectangle()
                    .aspectRatio(1.0, contentMode: .fit)
                    .border(color)
                    .foregroundColor(pixel.isColored ? color:.clear)
            }
        }
        
    }
}

struct TotalView_Previews: PreviewProvider {
    static var previews: some View {
        TotalView()
    }
}
struct Pixel:可识别、可散列{
变量id:Int
var isColored:Bool
}
类模型:ObservieObject{
@已发布的变量像素:[像素]
初始(总像素:Int){
像素=(1…totalPixels).map{Pixel(id:$0,isColored:false)}
}
func pixelsRange(num:Int,clusterDimension:Int)->[像素]{

返回数组(像素[(num-1)*clusterDimension..尝试使用此数组更改您的方法:

func startFillingAllAnimated() {
    DispatchQueue.global().async {
        for idx in self.pixels.indices {
            Thread.sleep(forTimeInterval: 0.03)
            DispatchQueue.main.async {
                self.pixels[idx].isColored = true
            }
        }
    }
}

部分问题在于此代码:

func startFillingAllAnimated() {
    
    for idx in pixels.indices {
        let addTime = idx
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(addTime) * 0.1) {
            self.pixels[idx].isColored = true
        }
    }
}
在一个非常紧密的循环中运行,并且几乎在瞬间执行

您可以通过在末尾添加
print()
语句来确认:

func startFillingAllAnimated() {
    
    for idx in pixels.indices {
        let addTime = idx
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(addTime) * 0.1) {
            self.pixels[idx].isColored = true
        }
    }

    print("returning")
}
在第一个方格变为填充之前,您将在调试控制台中看到打印的“returning”

因此,所有对
.asycAfter
的调用都已排队,UI更新“阻塞”

您可能想尝试这种方法

我们将创建一个计时器,每次计时器重复时填充数组中的下一个网格方块。这样,我们一次只在一个方块上设置
.isColored
,并且,作为一个附加的好处,它为我们提供了一种在“网格填充”完成之前停止进程的方法(例如添加一个“停止”按钮来跟随“开始”按钮:

模型
类变为:

class Model: ObservableObject {
    
    @Published var pixels: [Pixel]
    
    // so we can interrupt the filling loop
    @Published var keepRunning: Bool = false
    
    init(totalPixels: Int) {
        pixels = (1...totalPixels).map{ Pixel(id: $0, isColored: false)}
    }
    
    func pixelsRange(num:Int, clusterDimension:Int) -> [Pixel]{
        return Array(pixels[(num-1)*clusterDimension..<clusterDimension*num])
    }
    
    func startFillingAllAnimated() {
        // if "start" button tapped,
        //  "un-color" all the pixels
        for idx in self.pixels.indices {
            self.pixels[idx].isColored = false
        }
        // start filling them
        resumeFilling()
    }
    
    func resumeFilling() {
        // if ALL pixels are already "colored" don't do anything (just return)
        guard let i = pixels.firstIndex(where: {$0.isColored == false}) else { return }
        // set the running flag
        keepRunning = true
        DispatchQueue.global().async {
            // start at the first non-colored pixel
            for idx in i..<self.pixels.count {
                // insert a slight delay
                //  based on quick testing...
                //  0.0020 will take about 3 seconds to fill them all
                //  0.0010 will take about 1.5 seconds to fill them all
                //  0.0002 will take about 0.3 seconds to fill them all
                //  anything shorter pretty much fills them all instantly
                //  so, you probably want somewhere between
                Thread.sleep(forTimeInterval: 0.0010)
                DispatchQueue.main.async {
                    self.pixels[idx].isColored = true
                }
                // if keepRunning was set to false, break out of the loop
                if !self.keepRunning {
                    break
                }
            }
        }
    }

    // call this if we want to Stop
    //  before the grid has been completely filled
    func stopFilling() {
        self.keepRunning = false
    }
    
}
类模型:ObservableObject{
@已发布的变量像素:[像素]
//所以我们可以中断填充循环
@已发布变量keepRunning:Bool=false
初始(总像素:Int){
像素=(1…totalPixels).map{Pixel(id:$0,isColored:false)}
}
func pixelsRange(num:Int,clusterDimension:Int)->[像素]{

返回数组(像素[(num-1)*clusterDimension..它工作正常,但如果我缩短时间间隔,则需要花费大量时间来填充所有内容,有没有快速完成的想法?@SimonePistecchia-请参阅我答案中的编辑。工作正常:)
    Button("start") {
        model.startFillingAllAnimated()
    }
    Button("stop") {
        model.stopFilling()
    }
    Button("resume") {
        model.resumeFilling()
    }
class Model: ObservableObject {
    
    @Published var pixels: [Pixel]
    
    // so we can interrupt the filling loop
    @Published var keepRunning: Bool = false
    
    init(totalPixels: Int) {
        pixels = (1...totalPixels).map{ Pixel(id: $0, isColored: false)}
    }
    
    func pixelsRange(num:Int, clusterDimension:Int) -> [Pixel]{
        return Array(pixels[(num-1)*clusterDimension..<clusterDimension*num])
    }
    
    func startFillingAllAnimated() {
        // if "start" button tapped,
        //  "un-color" all the pixels
        for idx in self.pixels.indices {
            self.pixels[idx].isColored = false
        }
        // start filling them
        resumeFilling()
    }
    
    func resumeFilling() {
        // if ALL pixels are already "colored" don't do anything (just return)
        guard let i = pixels.firstIndex(where: {$0.isColored == false}) else { return }
        // set the running flag
        keepRunning = true
        DispatchQueue.global().async {
            // start at the first non-colored pixel
            for idx in i..<self.pixels.count {
                // insert a slight delay
                //  based on quick testing...
                //  0.0020 will take about 3 seconds to fill them all
                //  0.0010 will take about 1.5 seconds to fill them all
                //  0.0002 will take about 0.3 seconds to fill them all
                //  anything shorter pretty much fills them all instantly
                //  so, you probably want somewhere between
                Thread.sleep(forTimeInterval: 0.0010)
                DispatchQueue.main.async {
                    self.pixels[idx].isColored = true
                }
                // if keepRunning was set to false, break out of the loop
                if !self.keepRunning {
                    break
                }
            }
        }
    }

    // call this if we want to Stop
    //  before the grid has been completely filled
    func stopFilling() {
        self.keepRunning = false
    }
    
}