问题描述
我对 Swift 和 SwiftUI 编程还很陌生,但我又遇到了一个奇怪的问题。
我的目标是读取文本字段中的变量,并在用户单击返回 (oncommit) 后将变量打印为注释。
我尝试使用单个 $comment 变量,但是一旦用户在文本字段中输入,它就会更新两个文本结果。
我的目标是让用户能够在文本字段中输入,而变量只会出现在文本字段下的部分中:("Your Comment is:"")
这是我第一次在 Stack Overflow 上发帖,对不起,如果我添加了太多代码。
import SwiftUI
struct ContentView: View {
private var numberofImages = 7
private let timer = Timer.publish(every: 3,on: .main,in: .common).autoconnect()
@State private var currentIndex = 0
@State private var comment:String = ""
@State private var userComment:String = ""
@State private var showComment:Bool = false
func prevIoUs() {
withAnimation {
currentIndex = currentIndex > 0 ? currentIndex - 1 : numberofImages - 1
}
}
func next() {
withAnimation{
currentIndex = currentIndex < numberofImages ? currentIndex + 1 : 0
}
}
var controls: some View {
HStack{
Button {
prevIoUs()
} label: {
Image(systemName: "chevron.left")
}
Spacer().frame(width:100)
Button {
next()
} label: {
Image(systemName: "chevron.right")
}
.accentColor(.primary)
}
}
var body: some View {
NavigationView{
GeometryReader { proxy in
vstack {
ScrollView{
TabView(selection: $currentIndex) {
ForEach(1..<numberofImages) {
num in Image("\(num)")
.resizable()
.scaledToFill()
.overlay(Color.black.opacity(0.4))
.tag(num)
}
}.tabViewStyle(PageTabViewStyle())
.clipShape(RoundedRectangle(cornerRadius: 9))
.frame(width: proxy.size.width,height: proxy.size.height / 3)
.onReceive(timer,perform: { _ in
next()
})
controls
.padding()
Text("Product Description").font(.largeTitle).bold()
Text("""
Incredibly light and boasting a speedy performance,get your work done anywhere with the MacBook Air (2020). From video-editing to gaming,the Apple M1 chip lets you take on the biggest tasks without draining your battery.
It's 3.5x faster than the prevIoUs generation,with eight-cores of power providing an incredible performance. And for whisper-quiet operation,the improved thermal efficiency means it doesn't even need a fan.
With the Retina display screen,everything from blockbuster movies to everyday browsing is a visual joy.
True Tone technology automatically adjust the display to your environment - so web pages and emails look as natural as if they were printed.
""") .padding() //.frame(width: 300,height: 300,alignment: .topLeading)
//Comment Text Field will need to go here. So it can be included within the scroll view.
TextField("",text: $comment,onEditingChanged: {_ in
self.showComment = true
},onCommit: {
if self.showComment {
self.comment = self.userComment
}
})
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("Your Comment is: \(self.userComment)")
// rating Section will need to go her as well. SystemName:Star.circle.fill or unfill.
}
}
解决方法
只需替换:
self.comment = self.userComment
与:
self.userComment = self.comment
您在文本 (userComment
) 中显示 Text("Your Comment is: \(self.userComment)")
,而 comment
是 TextField
的当前文本。