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

SwiftUI中如何为被容器裁剪的文本添加省略号?

SwiftUI中如何为被容器裁剪的文本添加省略号?

嗨,我来帮你搞定这个问题!你现在碰到的情况是,文本被容器直接切掉了,但没自动显示省略号——这是因为你用了.clipped()强行砍掉超出部分,却没给Text开启自动截断的逻辑,再加上原来的布局设置让Text根本不知道自己的空间有限。

问题根源

你代码里的.fixedSize(horizontal: false, vertical: true)会让VStack在垂直方向无限延伸,然后靠.frame(height: 330)加.clipped()硬把超出的部分砍掉。这种情况下,Text完全没察觉到自己被限制了,自然不会触发截断加省略号的机制。

解决方案

只需要调整布局设置,让Text感知到可用空间,同时开启截断模式就行:

  1. 移除.fixedSize(horizontal: false, vertical: true),让VStack适应容器的高度限制
  2. 给每个内容Text添加自动截断配置(默认截断模式就是末尾加省略号,重点是让Text知道空间有限)
  3. 不需要.clipped(),因为Text会自动截断,不会超出容器范围

修改后的完整代码如下:

import SwiftUI
import PlaygroundSupport

struct TruncatedTripView: View {
  
  let purpose = "Experience cultural diversity, visit iconic sites like Big Ben and Stonehenge, and savor British cuisine"

  let activity = "Taking the Jacobite Steam Train in Scotland, better known as the “Hogwarts Express, through breathtaking highland landscapes."
  
  let goal = "Explore historic landmarks, immerse in British culture, and enjoy the scenic countryside."

  let fact = "The UK is home to the oldest underground railway system, the London Underground, which began operations in 1863"
   
  var body: some View {
     VStack(alignment: .leading, spacing: 12.0) {
        VStack(alignment: .leading) {
            Text("Trip Purpose")
              .font(.headline)
            Text(purpose)
              .lineLimit(nil) // 允许自动换行,空间不足时自动截断
              .truncationMode(.tail) // 末尾添加省略号(默认就是该模式,可省略)
         }
                 
          VStack(alignment: .leading) {
              Text("Destination Facts")
                 .font(.headline)
              Text(fact)
                .lineLimit(nil)
                .truncationMode(.tail)
          }
      
         VStack(alignment: .leading) {
              Text("Most Excited Activity")
                .font(.headline)
              Text(activity)
                .lineLimit(nil)
                .truncationMode(.tail)
          }

          VStack(alignment: .leading) {
              Text("Goal")
                .font(.headline)
              Text(goal)
                .lineLimit(nil)
                .truncationMode(.tail)
          }
     }
     .frame(width: 360, height: 330, alignment: .top)
     // 无需.clipped(),Text会自动处理截断逻辑
 }
}

// Present the view controller in the Live View window
PlaygroundPage.current.setLiveView(TruncatedTripView())

进阶优化:控制截断优先级

如果你希望某些模块优先显示完整内容,最后只截断特定模块(比如你例子里的Goal),可以给其他模块添加.layoutPriority(),让它们优先占用空间:

// 给Trip Purpose模块设置更高优先级,优先显示完整内容
VStack(alignment: .leading) {
    Text("Trip Purpose")
        .font(.headline)
    Text(purpose)
        .lineLimit(nil)
        .truncationMode(.tail)
}
.layoutPriority(1)

这样高优先级的模块会先获取足够空间,最后剩下的空间留给Goal模块,不够的话Goal就会自动截断并显示省略号啦~

备注:内容来源于stack exchange,提问作者Jobie J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 08:35:31