当前位置: 首页 > news >正文

SwiftUI 1.Text介绍和使用

SwiftUI 的 Text 是用于显示静态文本的核心组件,它提供了丰富的样式和布局控制。以下是 Text 的详细介绍和使用示例:


一、基础用法

1. 显示简单文本
Text("Hello, SwiftUI!")
2. 设置字体样式
Text("Hello, SwiftUI!").font(.title)          // 系统字体(如 .title, .body, .caption).fontWeight(.bold)     // 字重(.light, .medium, .black 等).italic()              // 斜体.underline()           // 下划线
3. 修改颜色和对齐
Text("Hello, SwiftUI!").foregroundColor(.blue)  // 文字颜色.multilineTextAlignment(.center) // 多行对齐方式.frame(width: 200)       // 控制布局范围

二、高级功能

1. 多行文本与截断
Text("This is a long text that might need to wrap or truncate.").lineLimit(3)                // 最多显示3行.truncationMode(.tail)        // 截断位置(.head, .middle, .tail).lineSpacing(10)              // 行间距
2. Markdown 支持(iOS 15+)
Text("**Bold Text** *Italic* [Link](https://apple.com)")// 直接渲染 Markdown
3. 本地化字符串
Text("welcome_message", tableName: "Localizable")// 使用 Localizable.strings 中的键值
4. 格式化日期、数字等
Text(Date(), style: .date)       // 显示日期(如 "June 23, 2023")
Text(100.0, format: .currency(code: "USD")) // 格式化为 "$100.00"

三、自定义样式

1. 组合不同样式的文本
Text("Hello ")+ Text("SwiftUI").foregroundColor(.red).bold()
2. 使用 AttributedString(iOS 15+)
var attributedText: AttributedString {var text = AttributedString("Custom Style")text.font = .titletext.foregroundColor = .purplereturn text
}Text(attributedText)
3. 添加阴影和边框
Text("Stylish Text").shadow(color: .gray, radius: 2, x: 1, y: 1).border(.green, width: 1)

四、与其他组件结合

1. 在布局容器中使用
VStack {Text("First Line")Text("Second Line").padding()
}
2. 结合 Image
HStack {Text("Apple Logo")Image(systemName: "applelogo")
}

五、常见问题

  1. 动态内容更新Text 会自动响应绑定的数据变化。

    @State var count = 0
    Text("Count: \(count)") // 当 count 变化时自动更新
    
  2. 性能优化:避免在频繁更新的内容中使用复杂样式。

  3. 自定义字体

    Text("Custom Font").font(.custom("AvenirNext-Regular", size: 20))
    

六、完整示例

struct ContentView: View {@State private var counter = 0var body: some View {VStack(spacing: 20) {Text("Welcome!").font(.largeTitle).foregroundColor(.indigo)Text("You have \(counter) items").font(.body).foregroundColor(.secondary)Button("Add") { counter += 1 }}}
}

通过灵活组合这些功能,你可以轻松实现从简单标签到复杂富文本的展示需求。

相关文章:

  • 基于缺失数据的2024年山东省专项债发行报告
  • Linux进程状态及转换关系
  • 电池大脑的基准测试及AI拓展
  • React性能优化
  • Linux避免文件误删详解(Linux Avoids File Deletion Errors with Detailed Explanation)
  • 前缀和相似题共赏
  • 天梯-这是字符串题
  • Unity 接入阿里的全模态大模型Qwen2.5-Omni
  • VS中回显109:对‘pthread_create’未定义的引用
  • 服务器如何修复SSL证书错误?
  • 【Java面试笔记:基础】9.对比Hashtable、HashMap、TreeMap有什么不同?
  • 模型上下文协议MCP
  • pycharm调试typescript
  • Oracle 数据库中的 JSON:性能注意事项
  • 【CSS】层叠,优先级与继承(四):层叠,优先级与继承的关系
  • Elasticsearch 集群节点下线方案
  • SwiftUI 3.Button介绍和使用
  • Kimi做内容社区,剑指小红书?
  • AI赋能社区生态:虎跃办公的网址导航革新实践
  • 事业单位体检心电图不合格类型有哪些
  • 鲁迅先生儿媳、周海婴先生夫人马新云女士逝世,享年94岁
  • 结婚这件事,年轻人到底怎么想的?
  • 华夏幸福:去年营业收入237.65亿元,同比减亏12亿元
  • IMF前副总裁朱民捐赠1000万元,在复旦设立青云学子基金
  • 陈文清:推进扫黑除恶常态化走深走实,有力回应人民群众对安居乐业的新期待
  • 上汽集团一季度净利润30.2亿元,同比增长11.4%