SwiftUI: создайте представление как список, но с другим макетом - PullRequest
0 голосов
/ 22 апреля 2020

Редактировать с некоторыми кодами, которые могут быть использованы для воспроизведения проблемы. (Мое настоящее приложение будет иметь тысячи элементов в списке элементов.

Я работаю над небольшим приложением, использующим SwiftUI. У меня есть представление, которое зависит от данных для перерисовки некоторых элементов, например,

import SwiftUI

struct MyItem: Identifiable {
    var id: String = UUID().uuidString
    var name: String
    var yearsOfUse: Double
}

struct MyView: View {
    @Binding var aListOfItems: [MyItem]
    var body: some View {
            VStack(){
                ForEach(aListOfItems){item in
                    Text(item.name)
            }
        }
    }
}

struct ContentView: View {
    @State var items: [[MyItem]]
    @State var currentList: [MyItem]
    @State var currentListIndex: Int

    var body: some View {
        VStack(){
            Button(action: {
                if self.currentListIndex < self.items.count {
                    self.currentListIndex += 1
                    self.currentList = self.items[self.currentListIndex]
                }
            }){
                Text("Next")
            }.disabled(self.currentListIndex >= self.items.count - 1)
            Spacer()
            MyView(aListOfItems: $currentList)
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var items : [[MyItem]] = [[MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                     [MyItem(name:"CopyPaper", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0), MyItem(name:"BallPen", yearsOfUse:1.0)],
                                     [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Rubbers", yearsOfUse:1.0)],
                                     [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Siccer", yearsOfUse:2.0), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                     [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0)]]

    static var currentItem = items[0]
    static var currentIndex = 0
    static var previews: some View {
        ContentView(items: items, currentList: currentItem, currentListIndex: currentIndex)
    }
}

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let items : [[MyItem]] = [[MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                         [MyItem(name:"CopyPaper", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0), MyItem(name:"BallPen", yearsOfUse:1.0)],
                                         [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Rubbers", yearsOfUse:1.0)],
                                         [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Siccer", yearsOfUse:2.0), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                         [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                        [MyItem(name:"CopyPaper", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0), MyItem(name:"BallPen", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen2", yearsOfUse:0.5), MyItem(name:"Rubbers", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen3", yearsOfUse:0.5), MyItem(name:"Siccer1", yearsOfUse:2.0), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil2", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Siccer", yearsOfUse:2.0), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                        [MyItem(name:"CopyPaper", yearsOfUse:0.5), MyItem(name:"Pencil", yearsOfUse:1.0), MyItem(name:"BallPen", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen2", yearsOfUse:0.5), MyItem(name:"Rubbers", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen3", yearsOfUse:0.5), MyItem(name:"Siccer1", yearsOfUse:2.0), MyItem(name:"Pencil", yearsOfUse:1.0)],
                                        [MyItem(name:"Pen", yearsOfUse:0.5), MyItem(name:"Pencil2", yearsOfUse:1.0)]]

        let currentItem = items[0]
        let currentIndex = 0
        let contentView = ContentView(items: items, currentList: currentItem, currentListIndex: currentIndex)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

MyView - это представление, встроенное в представление содержимого, и каждый раз, когда я нажимаю кнопку в представлении содержимого, оно изменяет значение aListOfItem, которое может содержать различные элементы. Например, в первый раз Я нажимаю, aListOfItem содержит 5 элементов, и второй раз он содержит 7. Элемент, когда я тестировал в симуляторе, я обнаружил, что каждый раз, когда он создает новое представление текста на основе количества элементов, следовательно, память продолжает увеличиваться.

Я хотел бы реализовать этот вид списка, который позволяет повторно использовать текстовое представление, созданное ранее, поскольку я знаю, что максимальное количество элементов в aListOfItem равно 12.

Большое спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...