How do I modify the background color of a List in SwiftUI?

后端 未结 14 1322
醉酒成梦
醉酒成梦 2020-12-03 02:33

I\'m trying to recreate an UI I built with UIKit in SwiftUI but I\'m running into some minor issues.

I want the change the color of the List here, but n

14条回答
  •  执笔经年
    2020-12-03 02:51

    I've inspired some of the configurator used to config per page NavigationView nav bar style and write some simple UITableView per page configurator not use UITableView.appearance() global approach

       import SwiftUI
    
        struct TableViewConfigurator: UIViewControllerRepresentable {
    
            var configure: (UITableView) -> Void = { _ in }
    
            func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIViewController {
    
                UIViewController()
            }
    
            func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext) {
    
                let tableViews = uiViewController.navigationController?.topViewController?.view.subviews(ofType: UITableView.self) ?? [UITableView]()
    
                for tableView in tableViews {
                    self.configure(tableView)
                }
            }
        }
    

    Then there is UIView extension needed to find all UITableViews

    extension UIView {
        func subviews(ofType WhatType:T.Type) -> [T] {
            var result = self.subviews.compactMap {$0 as? T}
            for sub in self.subviews {
                result.append(contentsOf: sub.subviews(ofType:WhatType))
            }
            return result
        }
    }
    

    And usage at the end is:

    List {
    
    }.background(TableViewConfigurator {
        $0.backgroundColor = .red
    })
    

    Maybe one thing should be improved that is usage of navigationController?.topViewController to make it work even without navigationController in view controllers hierarchy

提交回复
热议问题