无法使用 SwiftUI 在列表中显示整个字符串
Posted
技术标签:
【中文标题】无法使用 SwiftUI 在列表中显示整个字符串【英文标题】:Can't show the whole string in a list using SwiftUI 【发布时间】:2021-07-12 07:17:25 【问题描述】:当你打开sample project:
先按一行,会出现一个加号按钮。点击一次加号按钮后,将在行中附加一个加号。如果我多次点击按钮,++++
字符串将显示+...
(如下图所示)。我没想到会这样,我希望行高会自动增加,因此可以显示整个字符串。我该怎么做才能解决它?
如果我点击加号按钮 5-6 次,行高将按预期自动增加。
主要项目代码在sample project:
ContentView.swift
struct ContentView: View
@EnvironmentObject var userData: UserData
var body: some View
HStack
List
ForEach(userData.subtasks) subtask in
SubtaskRowNextToCard(subtaskModel: subtask)
if userData.currentSubtask != nil
SubtaskCard()
.padding(.all)
.onAppear
for _ in 0..<20
appendASubtask()
func appendASubtask()
let aSubtask = SubtaskModel(
score: ""
)
userData.subtasks.append(aSubtask)
SubtaskModel.swift
import Foundation
import SwiftUI
class SubtaskModel: ObservableObject, Identifiable
@Published var score: String = ""
init(
score: String
)
self.score = score
SubtaskRowNextToCard.swift
struct SubtaskRowNextToCard: View
@ObservedObject var subtaskModel: SubtaskModel
@EnvironmentObject var userData: UserData
@State var scoreWithRound: String = ""
var body: some View
Button(action:
userData.currentSubtask = subtaskModel
)
Text(scoreWithRound)
.onAppear
updateScore()
.onReceive(NotificationCenter.default.publisher(for: NSNotification.Name.init("changedCurrentSubtask"))) obj in
updateScore()
func updateScore()
scoreWithRound = subtaskModel.score
SubtaskCard.swift
struct SubtaskCard: View
@EnvironmentObject var userData: UserData
var body: some View
Button(action:
print("+ button was tapped")
appendScore(newScore: "+")
)
Image(systemName: "plus.circle.fill")
.buttonStyle(PlainButtonStyle())
func appendScore(newScore: String)
if let subtaskModel = userData.currentSubtask
subtaskModel.score = subtaskModel.score + newScore + " "
NotificationCenter.default.post(name: NSNotification.Name.init("changedCurrentSubtask"), object: nil, userInfo: nil)
【问题讨论】:
【参考方案1】:添加.fixedSize(horizontal: false, vertical: true)
,它将不再截断文本:
ForEach(userData.subtasks) subtask in
SubtaskRowNextToCard(subtaskModel: subtask).fixedSize(horizontal: false, vertical: true)
编辑: 对于动态高度修复:
将Text
替换为TextEditor
,您不会注意到闪烁:
Text(scoreWithRound)
到
TextEditor(text: $scoreWithRound).allowsHitTesting(false)
【讨论】:
它有效,但并没有完美地解决问题。行的高度将是意外的(小于正常高度)See this example。点击加号按钮几次后the height becomes normal again 更新了答案,现在检查它是否适合你。以上是关于无法使用 SwiftUI 在列表中显示整个字符串的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI 试图从列表中删除对象但无法在不可变值上使用变异成员:是一个“让”常量