Код: Выделить всё
import SwiftUI
import AVFoundation
struct HomeView: View {
@State private var text2 = ""
let synthsizer = AVSpeechSynthesizer()
let impactRigid = UIImpactFeedbackGenerator(style: .rigid)
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
@State private var voices = true
@State private var current_voice = true
@State private var isalertshown = false
@FocusState private var iskeyboard: Bool
@EnvironmentObject var dataa: Data
var body: some View {
NavigationStack{
VStack {
Spacer()
ZStack(alignment: .trailing){
TextField("Enter Text and click Speak", text: $text2)
.textFieldStyle(.roundedBorder)
.keyboardType(.default)
.autocorrectionDisabled()
.multilineTextAlignment(.leading)
.submitLabel(.done)
.focused($iskeyboard)
if !text2.isEmpty {
Button {
text2 = ""
}label: {
Image(systemName: "multiply.circle.fill")
.foregroundStyle(Color.gray)
}
.padding(.trailing, 4)
}
}.padding(3)
Button(action: {
if text2.isEmpty {
iskeyboard = true
//isalertshown = true
impactHeavy.impactOccurred()
} else {
let utterance = AVSpeechUtterance(string: text2)
utterance.voice = AVSpeechSynthesisVoice(identifier: voices ? "com.apple.ttsbundle.Rishi-compact": "com.apple.ttsbundle.Lekha-compact")
synthsizer.speak(utterance)
impactRigid.impactOccurred()
}
}) {
Text("Speak")
.font(.title3)
.foregroundColor(.white)
.frame(width: 230, height: 40)
.background(Color.blue)
.cornerRadius(10)
}
//.alert(isPresented: $isalertshown) {
// Alert(title: Text("Error"), message: Text("Please input text in the above field"), dismissButton: .default(Text("OK")))
// }
Spacer()
Text("Current Voice: " + String(current_voice ? "Rishi": "Lekha"))
Menu {
Button {
voices = true
current_voice = true
}
label: {
Text("Rishi")
}
Button {
voices = false
current_voice = false
}
label: {
Text("Lekha")
}
}
label: {
Text("Change Voice")
}.disabled(dataa.changevoice == false)
}
.padding()
.navigationTitle("Text to Speech")
}
}
}
#Preview {
HomeView()
.environmentObject(Data())
}
class Data: ObservableObject {
@Published var changevoice = true
}
Код: Выделить всё
import SwiftUI
struct SettingsView: View {
@EnvironmentObject var data: Data
var body: some View {
NavigationView {
List {
Toggle(isOn: $data.changevoice) {
Text("Disable Voice Changing")
}.tint(.blue)
}.navigationTitle("Settings")
}
}
}
#Preview {
SettingsView()
.environmentObject(Data())
}
ЧТО Я ДЕЛАЮ НЕПРАВИЛЬНО? (Новичок)
есть два представления: домашний вид и просмотр настроек, переключатель находится в режиме просмотра настроек, а кнопка — в главном представлении, он принимает только значение, которое я передаю в классе.
Хотите чтобы переключить значение bool, чтобы можно было отключить кнопку в другом представлении, используя опубликованную переменную, но безуспешно
Подробнее здесь: https://stackoverflow.com/questions/781 ... bool-value
Мобильная версия