You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何随分段控件切换自动更改按钮文本

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 to UISegmentedControl, and choose the Value Changed event.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:39:10