我对Swift和SwiftUI编程还是个新手,我又遇到了一个奇怪的问题。
我的目标是读取文本字段中的变量,并在用户单击return (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.
}
}发布于 2021-05-06 04:23:13
只需替换:
self.comment = self.userComment通过以下方式:
self.userComment = self.comment您在文本(Text("Your Comment is: \(self.userComment)"))中显示userComment,而comment是TextField的当前文本。
https://stackoverflow.com/questions/67408248
复制相似问题