SwiftUI:VStack 中的 Text + TextField 导致“无法同时满足约束”。

Mic*_*ehn 5 ios swiftui

下面是在 VStack 中具有 Text 和 TextField 的应用程序的一些简约示例:

import SwiftUI

struct ContentView: View {
    @State private var textEntry : String = "Hello World"

    var body: some View {
        return VStack {
            Text(textEntry)
            TextField("Enter new text here", text: $textEntry)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)

该应用程序工作正常,即文本小部件显示您在文本字段小部件中键入的内容。问题是您收到布局约束无法得到满足的错误(或警告):

2020-12-29 10:31:13.800514+0100 SwiftuiTest[32286:2781544] [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. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x600001d50f00 h=--& v=--& _UIButtonBarButton:0x7fba5550cee0.height == 0   (active)>",
    "<NSLayoutConstraint:0x600001d4e7b0 _UIUCBKBSelectionBackground:0x7fba5550da00.bottom == _UIButtonBarButton:0x7fba5550cee0.bottom - 6   (active)>",
    "<NSLayoutConstraint:0x600001d4e710 V:|-(6)-[_UIUCBKBSelectionBackground:0x7fba5550da00]   (active, names: '|':_UIButtonBarButton:0x7fba5550cee0 )>"
)
Run Code Online (Sandbox Code Playgroud)

这里使用Stack是不是错了?基本上我只想有一些按钮、文本、文本字段小部件,它们使用显示器上的可用高度......

更新:

macOS 11.1 Xcode 12.3 (12C33)

iOS部署目标14.3 iOS模拟器:例如iPad(第8代)

$ xcodebuild -showsdks
iOS SDKs:
    iOS 14.3                        -sdk iphoneos14.3

iOS Simulator SDKs:
    Simulator - iOS 14.3            -sdk iphonesimulator14.3

macOS SDKs:
    DriverKit 20.2                  -sdk driverkit.macosx20.2
    macOS 11.1                      -sdk macosx11.1

tvOS SDKs:
    tvOS 14.3                       -sdk appletvos14.3

tvOS Simulator SDKs:
    Simulator - tvOS 14.3           -sdk appletvsimulator14.3

watchOS SDKs:
    watchOS 7.2                     -sdk watchos7.2

watchOS Simulator SDKs:
    Simulator - watchOS 7.2         -sdk watchsimulator7.2
Run Code Online (Sandbox Code Playgroud)

项目是在 Xcode 中创建的,具有接口SwiftUI和生命周期SwiftUI App。这将创建两个 Swift 源文件,例如SimpleTestApp.swiftContentView.swift

  • 文件ContentView.swift修改如上图
  • 文件SimpleTestApp.swift未修改,内容如下:
import SwiftUI

@main
struct SimpleTestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

War*_*ton 4

如果您查看日志中引用的类型_UIButtonBarButton_UIUCBKBSelectionBackground您可以看到布局异常发生在您不控制的私有元素中,位于 SwiftUI 下面的 UIKit 层中。_前面有一个的名字是一个很大的赠品。

\n

这种情况有时会发生,除非它影响 UI 的渲染,否则可以忽略。很烦人,但不是你能控制的。从这个角度来看,你可以认为这是一个警告。

\n