如何随分段控件切换自动更改按钮文本
Hey there! Let's get this sorted so your button updates automatically whenever the segmented control switches—no more relying on button taps to change the text. Here's a straightforward approach:
Step 1: Hook up the segmented control's value change event
First, we need to listen for when the user switches between the "Log In" and "Sign In" segments. How you do this depends on whether you built your UI in Storyboard/XIB or code:
If using Storyboard/XIB:
- Open your Storyboard, find the
UISegmentedControl, right-click and drag it to your ViewController class file. - In the pop-up menu, select Action, name the method something like
segmentedControlDidChange, set the type toUISegmentedControl, and choose theValue Changedevent.
If creating the segmented control in code:
Add this when setting up your segmented control to link it to a handler method:
let authSegmentedControl = UISegmentedControl(items: ["Log In", "Sign In"]) authSegmentedControl.addTarget(self, action: #selector(segmentedControlDidChange(_:)), for: .valueChanged) // Don't forget to add it to your view and set constraints if needed view.addSubview(authSegmentedControl)
Step 2: Update the button title in the handler method
Now write the method that will update your button's title based on the selected segment:
@objc func segmentedControlDidChange(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: // Selected "Log In" segment actionButton.setTitle("Log In", for: .normal) case 1: // Selected "Sign In" segment actionButton.setTitle("Sign In", for: .normal) default: // Fallback in case of unexpected index (optional) actionButton.setTitle("Log In", for: .normal) } }
Step 3: Set the initial button title
Make sure the button starts with the correct text matching the segmented control's default selected state. Add this to viewDidLoad:
override func viewDidLoad() { super.viewDidLoad() // Match the default selected segment (index 0 = "Log In" here) actionButton.setTitle("Log In", for: .normal) }
That's it! Now whenever the user toggles the segmented control, the button's title will automatically update to match the active segment—no extra button taps required.
内容的提问来源于stack exchange,提问作者Peter Brink

