如何解决无法使用 SwiftUI sample project 中的主要项目代码:
当您打开 sample project 时:
先按一行,会出现一个加号按钮。点击加号按钮一次后,将在行中附加一个加号。如果我多次点击按钮,++++
字符串将显示 +...
(如下图所示)。我没想到这一点,我希望行高会自动增加,以便可以显示整个字符串。我该怎么做才能修复它?
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)
}
}
}
解决方法
添加 .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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。