You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI的List嵌入UIKit后不显示内部Text组件的原因是什么?

问题根本原因

该问题由UIKit侧添加UIHostingController视图的约束配置错误导致:

  • List属于撑满父视图可用空间的容器组件,本身没有基于内容的自适应尺寸,当父视图(即UIHostingController的view)没有明确的宽高约束时,布局系统会给List计算出0尺寸的渲染区域,内部Text自然无法展示
  • 去掉List外层后,剩余的Text或普通自适应容器(如VStack)会基于内容计算自身尺寸,因此哪怕只有居中约束也能正常显示
修复方案

方案1:给UIHostingController的view添加撑满父视图的约束(最常用)

将原ViewController中center相关的约束替换为全屏约束即可:

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
        
    let swiftUIController = UIHostingController(rootView: DeviceView())

    addChild(swiftUIController)
    swiftUIController.view.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(swiftUIController.view)

    // 替换原有center约束为以下四条
    swiftUIController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    swiftUIController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    swiftUIController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    swiftUIController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    swiftUIController.didMove(toParent: self)
  }
}

方案2:给SwiftUI的List指定固定尺寸

如果你确实需要List居中展示不需要撑满全屏,可以直接在List上添加frame修饰符指定尺寸:

struct DeviceView: View {
  
  var body: some View {
    List {
      Text("First").foregroundColor(Color.red)
      Text("Second")
      Text("Third")
      Text("Fourth")
      Text("Fifth")
      Text("Sixth")
      Text("Seventh")
      Text("Eighth")
      Text("Ninth")
      Text("Tenth")
    }
    .font(.largeTitle)
    // 按需指定宽高即可
    .frame(width: 350, height: 600)
  }
}

内容的提问来源于stack exchange,提问作者Phantom59

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:06:00