我的Swift开发HarmonyOS相关

【潮汐】鸿蒙ArkUI中的LazyForEach和SwiftUI

2024-01-05  本文已影响0人  爱恨的潮汐

鸿蒙HarmonyOS开发ArkUI中的LazyForEach和SwiftUI中的ForEach的区别

SwiftUI 提供了三种不同的机制来构建一棵树的动态部分,ForEach就是其中之一。
ArkUI是鸿蒙的核心UI布局框架,除了ForEach,它还提供了LazyForEach,便于高性能开发。

image.png

由于ForEach往往和List搭配使用,我们会关注ForEach里的view是不是懒加载的,在SwiftUI中,只有ForEach,没有公开资料描述ForEach加载方式,在WWDC20-10031的材料中提到过:List里的内容总是以懒加载方式存在的。

然而测试发现,当list里的数据到达100000条后,初始化CPU占有率会达到100%,此时页面虽然显示了,但是无法滑动,即无响应状态。

List {
    ForEach(0..<100000){ I in
        ChatView(id: i)
    }
}

why is the swiftUI list not lazy (compared to lazyVStack)?
Bad performance of large SwiftUI lists on macOS

一种优化方式是给 List 里的内容加上固定高度,这样使用ForEach时SwiftUI就不需要计算每一个内容的高度了。

List {
    ForEach(0..<100000){ I in
        ChatView(id: i)
            .frame(width: 500, height: 15, alignment: .leading)
    }
}

此外,SwiftUI提供了LazyVStack和LazyHStack这两个容器,放在这两个容器中的内容是懒加载的。

相比SwiftUI,ArkUI中的LazyForEach无法实现以下场景:

1、SwiftUI中,可以使用ForEach直接遍历,可以通过$0获取索引。

VStack() {
    // 遍历从1-10,并创建从1-10的文本组件
    ForEach((1...10), id: \.self) {
        Text("\($0)…")
    }
}

2、可以直接对数组进行forEach,进行遍历:

let name = ["a","b","c","d"]

name.forEach {
    switch $0 {
    // 对name进行遍历,找到a
    case let x where x.hasPrefix("a"):
        print("\(x) is here")
    default:
        print("hi, \($0)")
    }
}
SwiftUI和ArkUI中的LazyForEach使用差异如下:

1、自由控制遍历的次数

在SwiftUI中,比如用数组的前一半数据绘制Text:

ForEach(0..<foo.count/2) { index in
    Text(foo[index])
}

在ArkUI中,以下代码报错:Argument of type ‘boolean’ is not assignable to parameter of type ‘any[]’.

ForEach(0..<foo.count/2,
  (item, index) => {
    ListItem() {
      Stack50View()
    }
  },
  (item) => item.toString()
)

2、List和ForEach搭配使用灵活性

在SwiftUI中,List中可以提供多个数据源和ForEach组合,比如在List中添加一组ForEach,添加一个Text后再添加一组ForEach:

List{
  ForEach(items,id:\.self){ item in
    Text(item)
  }
  Text("其他内容")
  ForEach(0..<10){ I in
    Text("id:\(i)")
  }
}

在ArkUI中,List中只能添加ListItem,以下代码报错:The ‘List’ component can have only the ListItem, Section and ListItemGroup child component.

List() {
  Text()
  ForEach(this.arr,
    (item, index) => {
      ListItem() {
        Stack50View()
      }
    },
    (item) => item.toString()
  )
  ForEach(this.arr,
    (item, index) => {
      ListItem() {
        Stack50View()
      }
    },
    (item) => item.toString()
  )
}

其他

SwiftUI中 ForEach内对数据增、删、改、查不需要通知框架层。
ArkUI中的LazyForEach需要告知框架层。

上一篇下一篇

猜你喜欢

热点阅读