Hi, does anyone know how to access buttons through a different view controller in Xcode? For example, in firstViewController I placed a button that is disabled, but once the user presses the button in the secondViewController, the button in firstViewController becomes enabled.
Accessing Buttons Through Different View Controllers
Is it UIKit or SwiftUI ?
If UIKit, you can use notification or delegation.
If SwifUI, use environment var or State var and Bindings.
Please confirm which case it is.
I’m using UIKit
So you could use notifications:
- declare a notification name
extension Notification.Name {
public static let kRefreshButton = Notification.Name("refreshButton")
}
- In FirstViewController, subscribe to notification
NotificationCenter.default.addObserver(self, selector: #selector(refreshButton(_:)), name: .kRefreshButton, object: nil)
- create the selector:
@objc func refreshPrefs(_ notification : Notification) {
button1.isEnabled = true
}
- Post a notification in secondViewController when button2 is pressed
@IBAction func romanEntered(_ sender: UIButton) {
NotificationCenter.default.post(name: .kRefreshButton, object: self)
}
Here is a similar in SwiftUI.
Don't forget to close the thread after this, by marking the correct answer. You will open new threads if needed later.
You'd better run in simulator, results in Preview are erratic.
struct SecondView: View {
@Environment(\.presentationMode) var presentation
@Binding var disabled : Bool
var body: some View {
ZStack {
Color.yellow
.ignoresSafeArea()
Button (action: {
disabled.toggle()
self.presentation
.wrappedValue.dismiss()
}) {
Text(disabled ? "Enable in First" : "Disable in First")
}
}
}
}
struct FirstView: View {
@State private var goNext = false
@State var buttonDisabled = true
var body: some View {
Spacer()
Button(buttonDisabled ? "I am disabled": "I am enabled") {
print("Now enabled")
}
.disabled(buttonDisabled)
Spacer()
Button("Go to second view") {
goNext.toggle()
}.sheet(isPresented: $goNext, content: {
SecondView2(disabled: $buttonDisabled) }
)
Spacer()
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}