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.
Replies
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
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)
}
-
Note that notification will work only if FirstViewController is loaded when you tap in SecondViewController (that is the case if you are in a navigation stack or if you present modally). Otherwise, you could save to userDefaults (in SecondViewController) and read userDefaults to set the button1 enabled or disabled in viewWillAppear in FirstViewController
-
Thank you so much and sorry to bother, but how would the other code look if I do use SwiftUI?
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()
}
}
-
Where do I place the "extension Notification.Name" code?
-
you place it anywhere at top level, outside of any class.
-
—
Claude31
Add a CommentIs it UIKit or SwiftUI ?