programing

Swift UI 탐색보기 탐색 모음제목 레이아웃 제약 조건 문제

sourcejob 2023. 8. 27. 09:06
반응형

Swift UI 탐색보기 탐색 모음제목 레이아웃 제약 조건 문제

이것은 최근에 출시된 XCode의 새로운 (12.3) 버전과 관련이 있을 수 있지만 저는 매우 간단한 Swift를 가지고 있습니다.UI 보기:

import SwiftUI

struct HomeView: View {
    var body: some View {
        NavigationView {
            Text("Text")
                .navigationBarTitle("My Title")
        }
    }
}

콘솔에서 다음 경고가 표시됩니다.

2020-12-15 18:25:06.506062-0800 Shopmatic[46177:9585655] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x600003636d00 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7faf15d0dc30]-(6)-[_UIModernBarButton:0x7faf15c17500'Your Lists']   (active)>",
    "<NSLayoutConstraint:0x600003636d50 'CB_Trailing_Trailing' _UIModernBarButton:0x7faf15c17500'Your Lists'.trailing <= _UIButtonBarButton:0x7faf15c16140.trailing   (active)>",
    "<NSLayoutConstraint:0x600003631e50 'UINav_static_button_horiz_position' _UIModernBarButton:0x7faf15d0dc30.leading == UILayoutGuide:0x600002c18ee0'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x600003631ea0 'UINavItemContentGuide-leading' H:[_UIButtonBarButton:0x7faf15c16140]-(0)-[UILayoutGuide:0x600002c18e00'UINavigationBarItemContentLayoutGuide']   (active)>",
    "<NSLayoutConstraint:0x600003617160 'UINavItemContentGuide-trailing' UILayoutGuide:0x600002c18e00'UINavigationBarItemContentLayoutGuide'.trailing == _UINavigationBarContentView:0x7faf15e10000.trailing   (active)>",
    "<NSLayoutConstraint:0x600003632580 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x7faf15e10000.width == 0   (active)>",
    "<NSLayoutConstraint:0x600003617520 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600002c18ee0'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':_UINavigationBarContentView:0x7faf15e10000 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600003636d00 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7faf15d0dc30]-(6)-[_UIModernBarButton:0x7faf15c17500'Your Lists']   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

이 간단한 예는 괜찮아 보이지만 좀 더 복잡한 것을 할 때:

import SwiftUI

struct ListDetailView: View {
    var list: List
    
    var body: some View {
        NavigationView {
            Text("Detail View")
            .navigationBarTitle("Detail View Title")
            .navigationBarTitleDisplayMode(.large)
            .navigationBarItems(
                trailing:
                    Button(action: {
                        print("Button Pressed")
                    }) {
                        Image(systemName: "ellipsis")
                }
            )
        }
    }
}

Navigation Title 영역 레이아웃이 모두 엉망이 되었습니다.

enter image description here

그것은 아무 상관이 없습니다.NavigationBarTitle. .navigationTitle사용되지 않습니다.단순 코드의 경우에도 새로운 X 코드 12.4 업데이트가 주요 문제인 것 같습니다.

var body: some View {
    NavigationView{
        Text("Hopefully will work this time")
            .navigationTitle("Error with constains")
    }
}

추가.navigationViewStyle(StackNavigationViewStyle())를 해결합니다.

var body: some View {
    NavigationView{
        Text("Yes it does!")
            .navigationTitle("Wow it works")
    }
    .navigationViewStyle(StackNavigationViewStyle())
}

NavigationBarTitle는 에서사않습다에서 더 사용되지 않습니다.iOS 14.3하지만 여전히 사용하고 싶다면, 추가를 시도해 보세요.navigationView그것이 경고를 고칠 것입니다.

       struct ContentView: View {
        var body: some View {
            NavigationView {
                VStack {
                    Text("Hello, world!")
                        .padding()
                    Spacer()
                }
                .navigationBarTitle("Hey there", displayMode: .inline)
            }
            .navigationViewStyle(StackNavigationViewStyle())
        }
    }

새로운 방법:

.navigationBarTitleDisplayMode(.inline)
.toolbar(content: {
     ToolbarItem(placement: .principal, content: {
     Text("Title")
  })})    

Xcode 13.0 베타 1

StackNavigationViewStyle 한정자를 추가하지 않으면 이로 인해 제약 조건 오류가 계속 발생합니다.

그나다대문는서에 문서는StackNavigationViewStyle상태:

이 형식을 직접 사용하지 마십시오.대신 스택을 사용합니다.

var body: some View {
    NavigationView {
        Text("Text")
            .navigationTitle("Title")
    }
    .navigationViewStyle(.stack)
}

탐색 모음제목은 iOS 14.3 https://developer.apple.com/documentation/swiftui/view/navigationbartitle(_:displaymode:)-8buvp 에서 더 이상 사용되지 않습니다.

내비게이션을 사용할 수 있습니다.제목 및 .navigationViewStyle(StackNavigationViewStyle())

import SwiftUI

struct HomeView: View {
    var body: some View {
        NavigationView {
            Text("Text")
                .navigationBarTitle("Hey there", displayMode: .inline)
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

위의 답변들이 모두 완전한 것은 아니기 때문에, 저는 이 질문을 오랫동안 연구해 왔고 이것이 제가 하게 된 것이기 때문에 덧붙이고 싶습니다.유용할 것 같습니다.

Navigation View의 흥미로운 점 중 하나는 대형 기기(일반적으로 iPhone 및 대형 iPad)에서도 분할 화면 기능을 수행하는 방법입니다.

var body: some View {
        NavigationView {
            Text("Primary")
        }
    }

iPhone11 ProMax의 가로 방향(Cmd + ->)으로 회전하면 텍스트 보기가 사라지는 것을 볼 수 있습니다.

SwiftUI는 자동으로 가로 탐색 보기를 고려하고 메인("기본") 대신 DetailView를 표시합니다.

당신은 스위프트 방식으로 문제를 해결할 수 있습니다.UI는 NavigationView 내부에 다음과 같은 두 가지 보기를 제공하여 기대합니다.

var body: some View {
        NavigationView {
            Text("Primary")
            Text("Secondary")
        }
    }

저는 명성이 거의 없기 때문에 링크가 있는 사진만 올릴 수 있습니다(제 게시물이 유용했다면 평가해주세요).

enter image description here

에 "Constraints"를 추가하면 "할 수 라는 오류가 발생합니다.. navigation Bar Title(Text ("Today's Flavors"), displayMode:. inline)

따라서 솔루션은 다음과 같습니다.

  1. 탐색 보기에 두 번째 보기 추가

여기서 화면을 돌리면 화면 #2 - 텍스트("보조")가 표시됩니다.

    var body: some View {
            NavigationView {
                Text("Primary")
                Text("Secondary")
            .navigationBarTitle(Text("Today's Flavors"), displayMode: .inline)
            }
    }
  1. 수어식.navigationViewStyle(StackNavigationViewStyle())

때첫Primary"))이("Primary")"를 ..navigationViewStyle(StackNavigationViewStyle) modifier())화면에 관계없이 항상 텍스트("기본")로 전환할 수 있습니다.

var body: some View {
        NavigationView {
            Text("Primary")
            Text("Secondary")
        .navigationBarTitle(Text("Today's Flavors"), displayMode: .inline)
        }
        .navigationViewStyle(StackNavigationViewStyle())

또한 여기에서 NavigationView에 대한 자세한 내용을 읽을 수 있습니다.

struct QuizView: View {
    var body: some View {

        NavigationView{
            Text("Hello, world!")
             .navigationBarTitle("Ripa", displayMode: .inline)
        }
        .navigationViewStyle(StackNavigationViewStyle()) /// add this line

    }
}

이 접근 방식을 사용할 때 제약 통지가 표시되지 않습니다.

import SwiftUI

struct ConstraintIssue: View {
    var body: some View {
        NavigationView {
            Text("Detail View")
                .toolbar(content: {
                    ToolbarItem(placement: .principal, content: {
                        Text("Detail View Title")
                    })
                    ToolbarItem(placement: .navigationBarTrailing, content: {
                      Button(action: {
                        print("Button Pressed")
                      }) {
                        Image(systemName: "ellipsis")
                      })
                   }
                }
            )
        }
    }
}

불행하게도, 많은 해결책들이 사용을 조언합니다.StackNavigationViewStyle()사이드바를 사용하는 iPad 앱을 만드는 경우에는 작동하지 않습니다.

이 선을 추가하면 조금 더 깊이 파고들 수 있습니다.

UserDefaults.standard.set(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")

의 느어쪽든 중 AppDelegate또는App인스턴스가 오류를 억제합니다.사용하지 않도록 설정했다는 경고가 한 줄 표시됩니다.스위프트를 사용하기 때문에 이것은 받아들일 수 있다고 생각합니다.UI 우리는 레이아웃 제약에 대해 걱정할 필요가 없으며, 우리가 스위프트를 사용하고 있기 때문에 애플이 기본적으로 이러한 것을 억제하기를 바랍니다.UI.

자세한 내용은 이 SO 답변을 참조하십시오.

오늘 Xcode 12.3으로 업데이트한 후 이 간단한 보기로 이러한 경고가 표시되지만 버그가 없는 정상으로 보입니다.그것은 새로운 Xcode 버전의 버그라고 추측합니다.

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Hello World")
                .navigationTitle("Hello World")
                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Button(action: {},
                            label: {
                            Image(systemName: "plus.circle")
                        })
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {},
                            label: {
                            Image(systemName: "plus.circle")
                        })
                    }
                }
        }
    }
}

다음은 경고입니다.

2020-12-16 14:25:05.897555+0800 TestingSwiftUI[76909:541649] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x600002847020 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7f7f7fc19680]-(6)-[_UIModernBarButton:0x7f7f8200ff20'HelloWorld']   (active)>",
    "<NSLayoutConstraint:0x600002847070 'CB_Trailing_Trailing' _UIModernBarButton:0x7f7f8200ff20'HelloWorld'.trailing <= _UIButtonBarButton:0x7f7f7fc18740.trailing   (active)>",
    "<NSLayoutConstraint:0x600002847de0 'UINav_static_button_horiz_position' _UIModernBarButton:0x7f7f7fc19680.leading == UILayoutGuide:0x6000032689a0'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x600002847ed0 'UINavItemContentGuide-leading' H:[_UIButtonBarButton:0x7f7f7fc18740]-(0)-[UILayoutGuide:0x6000032688c0'UINavigationBarItemContentLayoutGuide']   (active)>",
    "<NSLayoutConstraint:0x60000286a440 'UINavItemContentGuide-trailing' UILayoutGuide:0x6000032688c0'UINavigationBarItemContentLayoutGuide'.trailing == _UINavigationBarContentView:0x7f7f8200e2c0.trailing   (active)>",
    "<NSLayoutConstraint:0x60000285c410 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x7f7f8200e2c0.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000286a800 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x6000032689a0'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':_UINavigationBarContentView:0x7f7f8200e2c0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600002847020 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7f7f7fc19680]-(6)-[_UIModernBarButton:0x7f7f8200ff20'HelloWorld']   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

삭제할 때

.navigationTitle("Hello World")

경고가 사라졌습니다.

그래서 저는 이 문제를 애플에 보고할 것입니다.

이 보기는 정상적으로 보입니다.

저는 항상 같은 경고를 받았지만, 모든 것이 잘 작동합니다.말씀하신 대로 .navigation을 삭제합니다.제목(), 그리고 경고가 사라집니다, 그것은 벌레처럼 보입니다.

.navigationbar를 교체하기만 하면 됩니다..navigation이 포함된 제목("string")제목("string")이면 됩니다.그리고 .navigationViewStyle을 추가합니다.

이와 유사한 문제가 발생했습니다.

var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: SettingsView()) {
                    Text("Settings")
                }

                NavigationLink(destination: SettingsView()) {
                    Text("Restore Purchases")
                }
                
            }.navigationTitle(Text("More"))
        }
    }

이상하게도, 내비게이션을 움직이는 것은목록 내의 모든 항목에 대한 제목 수정:

var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: SettingsView()) {
                    Text("Settings")
                }

                NavigationLink(destination: SettingsView()) {
                    Text("Restore Purchases")
                }
                .navigationTitle(Text("More"))
            }
        }
    }

나는 이전에 그 내비게이션이제목은 Navigation View 내부에 포함되어 있는 한 모든 보기에 첨부할 수 있지만 분명히 그렇지 않습니다.다른 탐색 사례가 있습니다.제목()이 앱의 목록 보기에 첨부되어 정상적으로 작동하므로 이 특정 보기가 오류를 일으키는 이유를 알 수 없습니다.

작은 쪽지..내가 틀렸습니까? 아니면 ADC 코드가 틀렸습니까?

다음을 읽을 수 있습니다.

.navigationBarTitle(Text("Today's Flavors", displayMode: .inline)

그러나 BUT가 틀렸습니다. "구성원 '인라인'에 대한 컨텍스트 기반을 추론할 수 없습니다."

괄호를 잘못 배치했습니다.

올바른 코드:

.navigationBarTitle(Text("Today's Flavors"), displayMode: .inline)

코드를 완성합니다. 시도하려면...

import SwiftUI


struct ContentView: View {
    let items = ["Chocolate", "Vanilla", "Strawberry", "Mint Chip",
                    "Pistachio"]
       var body: some View {
            NavigationView {
                 List(items, id: \.self) {
                     Text($0)
                 }
                .navigationBarTitle(Text("Today's Flavors"), displayMode: .inline)
            }
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

PS

2021년 3월에 애플은 수정했습니다.하지만 가짜 코드로 복사본을 시도할 수 있습니다.예를 들어 다음과 같습니다.

https://gist.github.com/erica/6941e2adfce75807bcd64550b3669c26

저는 다음과 같은 관점에서 이 문제를 겪었습니다.

ScrollView(.vertical) {
    GeometryReader { proxy in
        LazyVGrid(
            columns: [GridItem(.flexible())],
            spacing: 8
        ) {
            ForEach(displayedTags, id: \.self) { tagName in
                LogTagView(
                    logger: logger,
                    name: tagName
                )
            }
        }
        .background(Color.clear)
    }
    .padding(.horizontal, 16)
}
.navigationTitle("Filter")

화면 크기가 작은 경우에만 문제가 발생한다는 것을 알게 되었습니다(예: iPhone SE 1세대).

저는 더 이상 사용되지 않는 것을 피해야 했습니다.navigationViewStyle수식어, 그래서 이 대답에 영감을 받아 - @eraleyebrows에서 - 첨부하여 해결했습니다.navigationTitle("Filter")로.ForEach:

ForEach(displayedTags, id: \.self) { tagName in
    LogTagView(
        logger: logger,
        name: tagName
    )
}
.navigationTitle("Filter")

이제 목록이 비어있을 수 있다는 문제가 하나 있어서, 저는 그 목록을 포장했습니다.ForEach안에서.Group보기 및 계속 작동:

Group {
    ForEach(displayedTags, id: \.self) { tagName in
        LogTagView(
            logger: logger,
            name: tagName
        )
    }
}
.navigationTitle("Filter")

이것은 iOS 15.4용 아이폰 SE 1s gen과 iOS 16.1용 아이폰 14 Pro Max에서 테스트되었습니다.

언급URL : https://stackoverflow.com/questions/65316497/swiftui-navigationview-navigationbartitle-layoutconstraints-issue

반응형