sourcetip

Swift에서 목록의 배경색을 수정하는 방법UI?

fileupload 2023. 9. 10. 12:30
반응형

Swift에서 목록의 배경색을 수정하는 방법UI?

UIKit으로 만든 UI를 스위프트에서 다시 만들어 보려고 합니다.UI를 사용하지만 사소한 문제가 발생했습니다.

저는 의 .List여기요, 하지만 제가 기대하는 것처럼 어떤 부동산도 작동하지 않는 것 같습니다.아래 샘플 코드:

struct ListView: View {
    @EnvironmentObject var listData: ListData

       var body: some View {
        NavigationView {
            List(listData.items) { item in
                ListItemCell(item: item)
            }
            .content.background(Color.yellow) // not sure what content is defined as here
            .background(Image("paper-3")) // this is the entire screen 
        }
    }
}

struct ListItemCell: View {
    let item: ListItem

    var body: some View {

        NavigationButton(destination: Text(item.name)) {
            Text("\(item.name) ........................................................................................................................................................................................................")
                .background(Color.red) // not the area I'm looking for
        }.background(Color.blue) // also not the area I'm looking for
    }
}

I want to change the WHITE area

좋아요, 목록 행을 색칠하는 해결책을 찾았습니다.

struct TestRow: View {

    var body: some View {
        Text("This is a row!")
        .listRowBackground(Color.green)
    }
}

그리고 몸 안에서:

List {
    TestRow()
    TestRow()
    TestRow()
}

제가 예상한 대로 작동하지만, 행 사이의 구분선을 제거하는 방법을 아직 찾지 못했습니다.

그러면 전체 목록의 배경이 녹색으로 설정됩니다.

init() {
   UITableView.appearance().separatorStyle = .none
   UITableViewCell.appearance().backgroundColor = .green
   UITableView.appearance().backgroundColor = .green
}

enter image description here

struct ContentView: View {

    var strings = ["a", "b"]

    var body: some View {

        List {
            ForEach(strings, id: \.self) { string in
                Text(string)
            }.listRowBackground(Color.green)
        }
    }
}

바꿈으로써 할 수 있습니다.UITableView의 모습.

UITableView.appearance().backgroundColor = UIColor.clear

은 그냥 됩니다에 .AppdelegatedidFinishLaunchingWithOptions. ⑥을 대신하여UIColor.clear할다을rf을nk에r할rutod.. .list.

배경색 변경

다른 사용자가 언급한 것처럼 UITableView 배경을 변경하면 앱의 다른 모든 목록에 영향을 미칩니다.

그러나 다른 배경색을 원할 경우 기본값을 지우기로 설정하고 배경색을 swiftui 보기에서 다음과 같이 설정할 수 있습니다.

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}
// Ignore safe area to take up whole screen
.background(Color.purple.ignoresSafeArea())
.onAppear {
    // Set the default to clear
    UITableView.appearance().backgroundColor = .clear
}

SceneDelegate 또는 root 보기와 같이 테이블 보기 모양을 더 일찍 설정할 수 있습니다.

// SceneDelegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
      
    
    guard let windowScene = scene as? UIWindowScene else {
        print("Returning because screne does not exist")
        return
            
    }
    
    // Set here    
    UITableView.appearance().backgroundColor = .clear
    let contentView = ContentView()
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = UIHostingController(rootView: contentView)
    self.window = window
    window.makeKeyAndVisible()
}


// Root App View
@main
struct ListBackgroundApp: App {
    
    init() {
        UITableView.appearance().backgroundColor = .clear
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Working Background Color Change

iOS 16은 List(및 기타 스크롤 가능한 뷰)의 배경 가시성을 제어하기 위한 수정자를 제공합니다: scroll ContentBackground(_:)

은 Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ ΔΔ Δ Δ Δ,.hidden이 a를 한다면 . background그것도 눈에 띕니다.

List {
    Text("One")
    Text("Two")
}
.background(Image("MyImage"))
.scrollContentBackground(.hidden)

목록 행의 배경(개별 셀)과 구분자를 사용자 정의할 수도 있습니다.이 작업은 다음과 같이 수행할 수 있습니다.

List {
    Section("Header") {
        Text("One")
        Text("Two")
            .listRowBackground(Color.red)
    }
    .listRowBackground(Color.clear)
    .listRowSeparator(.hidden)
}
.scrollContentBackground(.hidden)

2022

맥OS 솔루션

의 모든 을 의 모든 로 .List배경색 투명:

// Removes background from List in SwiftUI
extension NSTableView {
    open override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()
        
        backgroundColor = NSColor.clear
        if let esv = enclosingScrollView {
            esv.drawsBackground = false
        }
    }
}

enter image description here

..........

..........

..........

OLL ALL OLL ALL OLL ALL OLL ALL ALL ALL ALL ALL ALL ALL ALL ALL ALO.TextEditor배경색 투명:

extension NSTextView {
    open override var frame: CGRect {
        didSet {
            backgroundColor = .clear
            drawsBackground = true
        }
    }
}

Swift에서 listRowBackground()라는 인수가 있습니다.UI, 그러나 List를 직접 사용하여 데이터 수집을 반복하면 작동하지 않습니다.

다음은 제 해결 방법입니다.

    List {
        // To make the background transparent, we have we use a ForEach as a wrapper
        ForEach(files) {file in
            Label(
                title: { Text(file.name ?? fileOptionalFiller).lineLimit(listRowTextLineLimit) },
                icon: { AppIcon.doc.foregroundColor(.primary) }
            )
        }
        .listRowBackground(Color.primary.colorInvert())
    }

기본적으로 forEach inside List를 사용하는 경우 listRowBackground()가 작동합니다.

color Multiply(color : 색)를 사용하여 전체 목록이 색을 바꿀 수 있었습니다.목록 보기 끝에 이 수식어를 추가하면 패딩으로 테이블이 장치 가장자리로 밀려납니다.예를 들어,

List {...}.colorMultiply(Color.green).padding(.top)

https://www.hackingwithswift.com/quick-start/swiftui/how-to-adjust-views-by-tinting-and-desaturating-and-more

어떤 연관성이 있는지는 모르겠지만 목록을 다음과 같이 포장하면 됩니다.Form효과가 있습니다.

Form {
     List(viewModel.currencyList, id: \.self) { currency in
        ItemView(item: currency)
     }
      .listRowBackground(Color("Primary"))
      .background(Color("Primary"))
}
struct Details: View {

    var body: some View {
        Spacer().overlay(
            List {
                Text("Hello World!").font(.title2)
                    .listRowBackground(Color.clear)
                Text("Hello World again").font(.title2)
                    .listRowBackground(Color.clear)
            }.onAppear() {
                UITableView.appearance().backgroundColor = UIColor.green
                UITableViewCell.appearance().backgroundColor = UIColor.green
            }
        )
    }
}

Islom Alimov https://stackoverflow.com/a/59970379/9439097 의 답변이 지금까지 나온 것 중 가장 좋은 방법인 것 같습니다.

유일한 단점: 앱의 다른 모든 목록 보기의 배경색도 변경되므로 어디에서나 동일한 색을 원하지 않는 한 수동으로 다시 변경해야 합니다.

보기의 예시는 다음과 같습니다.

import SwiftUI

struct TestView1: View {
    
    init(){
        UITableView.appearance().backgroundColor = UIColor(Color.clear)
    }
    
    @State var data = ["abc", "def"]
    
    var body: some View {
        VStack {
            List {
                ForEach(data, id: \.self) {element in
                    Text("\(String(describing: element))")
                }
                .background(Color.green)
                .listRowBackground(Color.blue)
                
            }
            .background(Color.yellow)
            Spacer()
            Color.red
        }
    }
}

struct TestView1_Previews: PreviewProvider {
    static var previews: some View {
        TestView1()
    }
}

생산물:

Swift 하여 을 한 가 를 가 하여 한 을 를UI를 이용한 .listRowBackground그리고 적용하는 것.padding

var body: some View {
    NavigationView {
        List {
            ForEach (site) { item in
                HStack {
                    Text(String(item.id))

                    VStack(alignment: .leading) {
                        Text(item.name)
                        Text(item.crop[0])
                    }

                }.listRowBackground(Color.yellow)
                      .padding(.trailing, 5)
                      .padding(.leading, 5)
                      .padding(.top, 2)
                      .padding(.bottom, 2))
            }
        }
            .navigationBarTitle(Text("Locations"))
    }
}

수정자가 이렇게 해야 할 것 같은데 Xcode 11 Beta 11M336w 현재는 아닙니다.

var body: some View {
    List(pokemon) { pokemon in
        PokemonCell(pokemon: pokemon)
            .listRowPlatterColor(.green)
    }
}

.color멀티플라이(...)

으로 으로 할 수 ..colorMultiply(Color.yourColor)수식어가 붙은

경고: 색상이 변경되지 않습니다!이것은 오직 다음과 같은 경우에만 적용됩니다.Multiply현재 색상에 대한 수식어입니다."Swift에서 목록의 배경색을 변경하는 방법"을 찾고 있으므로 작업 전에 질문을 읽으십시오.UI", 이는 사용자에게 적합하지 않습니다. ❄️

예:

List (elements, id:\.self ) { element in

     Text(element)

}
.colorMultiply(Color.red) <--------- replace with your color

enter image description here

List in Swift의 배경을 바꿀 수 있는 완벽한 솔루션입니다.UI:

struct SomeView: View {
    init(){
    UITableView.appearance().backgroundColor = UIColor(named: "backgroundLight")
      }
...

}

아직 리스트가 완벽하지 않습니다.

입니다 - 도 의 가 하는 ->List { ForEach(elements) { }}에 대신에List($elements)

저는 이것이 지금까지 가장 잘 작동한 것입니다.@말한 @FontFamily의 것도 않아야 합니다List스와이프와 같은 기본 동작입니다.

추가하기 UITableView양의 모양 :init() style법및록일가가일d법(.listStyle(SidebarListStyle()) 수입해주세요. ㅜㅜㅜㅜㅜUIKit

struct HomeScreen: View {
init() {
    UITableView.appearance().backgroundColor = .clear
}

let tempData:[TempData] = [TempData( name: "abc"),
                         TempData( name: "abc"),
                         TempData( name: "abc"),
                         TempData( name: "abc")]

var body: some View {
    ZStack {
        Image("loginBackgound")
            .resizable()
            .scaledToFill()
        List{
            ForEach(tempData){ data in
                Text(data.name)
            }
        }
        .listStyle(SidebarListStyle())
        
    }
    .ignoresSafeArea(edges: .all)
}
}

UITableView.aperance().backgroundColor를 사용하면 모든 테이블의 backgroundColor가 변경되므로 사용하지 않는 것이 좋습니다.iOS 14, 15에서 선택하신 정확한 테이블에서 색상 변경을 위한 작동 솔루션을 찾았습니다.

리스트 내에 적용해야 하는 수정자를 사용하여 색상을 변경할 것입니다.

extension View {
    
    func backgroundTableModifier(_ color: UIColor? = nil) -> some View {
        self.modifier(BackgroundTableModifier(color: color))
    }

}

우리의 과제는 UITable View를 찾은 후 색상을 변경하는 것입니다.

private struct BackgroundTableModifier: ViewModifier {
    
    private let color: UIColor?
    @State private var tableView: UITableView?
    
    init(color: UIColor?) {
        self.color = color
    }
    
    public func body(content: Content) -> some View {
        if tableView?.backgroundColor != color {
            content
                .overlay(BackgroundTableViewRepresentable(tableBlock: { tableView in
                    tableView.backgroundColor = color
                    self.tableView = tableView
                }))
        } else {
            content
        }
    }
}

private struct BackgroundTableViewRepresentable: UIViewRepresentable {
    
    var tableBlock: (UITableView) -> ()
    
    func makeUIView(context: Context) -> BackgroundTableView  {
        let view = BackgroundTableView(tableBlock: tableBlock)
        return view
    }
    
    func updateUIView(_ uiView: BackgroundTableView, context: Context) {}
}

class BackgroundTableView: UIView {
    
    var tableBlock: (UITableView) -> ()
    
    init(tableBlock: @escaping (UITableView) -> ()) {
        self.tableBlock = tableBlock
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let tableView = findTableView(in: self) {
            tableBlock(tableView)
        }
    }
    
    private func findTableView(in view: UIView) -> UITableView? {
        if let tableView = view as? UITableView {
            return tableView
        }
        
        if let superView = view.superview {
            return findTableView(in: superView)
        }
        
        return nil
    }
    
}

UITableView를 찾으려면 수식어가 List 안에 있어야 합니다.당연히 수식어가 한 번만 호출되는지 확인해야 하며 각 행에 이 수식어를 적용할 필요는 없습니다.여기 사용 예시가 있습니다.

List {
   rows()
     .backgroundTableModifier(.clear)
}

func rows() -> some View {
    ForEach(0..<10, id: \.self) { index in
        Row()
    }
}

색상 변경이 작동하지 않는 이유로 .listStyle을 .plain으로 시도할 수 있습니다.

코드:

struct ContentView: View {
var body: some View {
    VStack {
        Text("Test")

        List {
            ForEach(1 ..< 4) { items in
                Text(String(items))
            }
        }
        .listStyle(.plain)
    }
}

iOS 16에서 우리는 스크롤 콘텐츠 배경 수정기를 통해 이를 수행할 수 있는 기본적인 방법을 얻었습니다.

색상을 설정하여 색상을 변경할 수 있습니다 (ShapeStyle) 로scrollcontentbackground.

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}
.scrollContentBackground(Color.pink)

아니면 배경을 숨길 수도 있습니다. .scrollContentBackground(.hidden)사용자 정의를 설정합니다..backgroud수식어가 붙은

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}
.background {
    Image("ventura")

}
.scrollContentBackground(.hidden)

시스템 배경 때문에 배경을 바꾸는 것은 저에게 효과가 없었습니다.숨길 필요가 있었어요

List(examples) { example in
        ExampleRow(example: example)
    }.background(Color.white.edgesIgnoringSafeArea(.all))
        .scrollContentBackground(.hidden)

페이지당 NavigationView 탐색 모음 스타일을 구성하고 UITableView를 사용하지 않는 간단한 페이지당 UITableView를 작성하는 데 사용되는 일부 구성자에게 영감을 주었습니다.apparence() 글로벌 접근 방식

   import SwiftUI

    struct TableViewConfigurator: UIViewControllerRepresentable {

        var configure: (UITableView) -> Void = { _ in }

        func makeUIViewController(context: UIViewControllerRepresentableContext<TableViewConfigurator>) -> UIViewController {

            UIViewController()
        }

        func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<TableViewConfigurator>) {

            let tableViews = uiViewController.navigationController?.topViewController?.view.subviews(ofType: UITableView.self) ?? [UITableView]()

            for tableView in tableViews {
                self.configure(tableView)
            }
        }
    }

그런 다음 모든 UITable View를 찾는 데 필요한 UIView 확장이 있습니다.

extension UIView {
    func subviews<T:UIView>(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
    }
}

마지막에 사용하는 방법은 다음과 같습니다.

List {

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

어쩌면 한 가지 개선되어야 할 것은 내비게이션 컨트롤러의 사용입니다.topViewController - 탐색 없이도 작동 가능하도록 보기Controller 계층 구조에 있는 Controller

iPhone X/11의 풀 너비가 아닌 배경 배경에 대한 솔루션을 찾고 있는 사람이 있다면 다음을 시도해 보십시오.

.listRowBackground(Color("backgroundColour").edgesIgnoringSafeArea(.all))

전체적으로 모든 테이블 보기에 대해 모양을 설정하지 않으려면 다음을 조합할 수 있습니다.UITableView.appearance(whenContainedInInstancesOf:)와 함께UIHostingController. 위에 언급해 주신 댄 스킬 씨께 감사드립니다.이렇게 사용했습니다.

public class ClearTableViewHostingController<Content>: UIHostingController<Content> where Content: View {
    public override func viewDidLoad() {
        UITableView.appearance(whenContainedInInstancesOf: [ClearTableViewHostingController<Content>.self]).backgroundColor = .clear
    }
}

사용가능ClearTableViewHostingController다음과 같이:

let view = MyListView()
let viewController = ClearTableViewHostingController(coder: coder, rootView: view)

그런 다음 보기에서 목록 배경색을 다음과 같이 설정할 수 있습니다.

List {
    Text("Hello World")
}
.background(Color.gray)

확장 목록을 다음과 같이 만듭니다.

extension List{
@available(iOS 14, *)
func backgroundList(_ color: Color = .clear) -> some View{
    UITableView.appearance().backgroundColor = UIColor(color)
    return self
}

}

사용가능introspectGithub의 library를 통해 기본 테이블 뷰의 배경색을 다음과 같이 설정할 수 있습니다.

List { ... } .introspectTableView { tableView in
                tableView.backgroundColor = .yellow
            }
import SwiftUI

extension View {
    func blurredSheet<Content: View>(_ style: AnyShapeStyle, isPresented: Binding<Bool>, onDismiss: @escaping ()->(), @ViewBuilder content: @escaping ()->Content) -> some View {
        self
            .sheet(isPresented: isPresented, onDismiss: onDismiss) {
                content()
                    .background(RemoveBackgroundColor())
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background {
                        Rectangle()
                            .fill(style)
                            .ignoresSafeArea(.container, edges: .all)
                    }
            }
    }
}

fileprivate struct RemoveBackgroundColor: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        return UIView()
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        DispatchQueue.main.async {
            uiView.superview?.superview?.backgroundColor = .clear
        }
    }
}

Xcode 버전 12.4

배경 부동산은 내게 효과가 있었지만 Opacity를 의무적으로 사용했습니다.불투명하지 않으면 그것은 작동하지 않습니다.

List {
            ForEach(data, id: \.id) { (item) in
                ListRow(item)
                    .environmentObject(self.data)
            }
        }
        .background(Color.black)
        .opacity(0.5)

언급URL : https://stackoverflow.com/questions/56517904/how-do-i-modify-the-background-color-of-a-list-in-swiftui

반응형