swift - 为 SwiftUI 文本视图提供固定宽度并使文本换行到不定高度
问题描述
主要编辑澄清问题
我想要什么:对于Text
与屏幕左侧或右侧对齐的视图,以扩展到某个最大宽度,并且当文本达到该长度时,它不会超过该长度。当要显示的文本变得太长时,Text
视图只是简单地增加高度以考虑额外的文本。这方面的一个例子是在 Apple 的 Messages 应用程序中:发送的消息一直向右对齐,但即使它们很长,它们的左边仍然有一个空白区域(聊天气泡的宽度只有 75%屏幕宽度)。
我有一些硬编码值来提供示例的代码:
struct ContentView: View {
let messages = [
"Hello.",
"Hi",
"Text so long that it could reach all the way to the other side of the screen, we only want it to take up a width of about 75% of the screen though starting from the left. That is the main issue of this post.",
"Yeah. This message is also long enough to take up the full width of the screen, but for this one we want it to take up 75% of the screen starting all the way on the right side.",
"What are we gonna do.",
"IDK."
]
var body: some View {
VStack {
List {
ForEach(0...5, id: \.self) { number in
Text(messages[number])
.frame(maxWidth: .infinity, alignment: number % 2 == 0 ? .leading : .trailing)
}
}
}
}
}
所以我几乎得到了我想要的,所有其他信息都是正确的。但是,当视图中的字符串很长时,视图Text
的宽度会在高度开始扩展之前一直扩展。我希望宽度仅在高度开始扩展之前扩展一定量。Text
我知道扩大Text
视图宽度以适应文本是正常行为,但我想知道是否有办法改变它。我唯一能想到的尝试是改变maxWidth
,但这只会导致右边缘.trailing
Text
向左移动,这是不需要的。
解决方案
ForEach(previouslyPlayed, id: \.self) { data in
Text(data.text)
.lineLimit(nil)
.multilineTextAlignment(.trailing)
.foregroundColor(ColorManager.mainText)
.font(.custom("Courier New", size: 14))
.fixedSize(horizontal: false, vertical: true)
}
推荐阅读
- html - 折叠按钮在使用引导程序的heroku上不起作用
- jquery - 如何在 Materialise 自动完成中使用动态数据?
- powershell - 获取用户密码过期日期 Powershell 并导出为 CSV
- python - 在 Azure Cosmos DB 中插入时分区键不起作用
- php - 使用 API 的 Shopify 产品元字段
- jquery - Laravel - JQuery keyup 仅在 Laravel json 中 parent_id 为 1 时有效
- node.js - 错误:此方法仅在ms team team范围内有效
- java - 在检票口的下拉菜单中选择“选择一个”后
- sql - 如何编写 SQL 脚本以在表中插入/更新数据
- javascript - 用 Google 表格上的相应代码 onEdit 替换选定的下拉列表选项