How do I change button text automatically with a segment change

时间:2018-02-03 10:35:44

标签: swift xcode uisegmentedcontrol

I want to create a log in screen for users, and so when they are on the "log in" segment of the segmented control, I want it to display "log in" on my button. However when the user switches to the "Sign in" segment I want the button to display "sign in" and not "log in". The only way I have gotten it to display "sign in" so far is by making the user click the button, and using actionButton.setTitle("sign in", for: .normal) to change the text, but I want it to happen automatically as soon as the user switches segment. Does anyone know how to do this?

This is what my view controller for the sign up page looks like

1 个答案:

答案 0 :(得分:0)

override func viewDidLoad() {
    super.viewDidLoad()
    segment.addTarget(self, action: #selector(valueDidChange(segment:)), for: .valueChanged)
}

func valueDidChange(segment: UISegmentControl) {
    switch segment.selectedIndex {
    case 0:
        actionButton.setTitle("log in", for: .normal)
    default:
        actionButton.setTitle("sign in", for: .normal)
    }
}