I have added a UISegmentedControl
in my application. None of the buttons are selected in normal state. I want to implement a button click event when the first segment is selected, and another event when another button is clicked.
A segmented control is a horizontal set of two or more segments. It's used as toggles for features or content, similar to radio buttons but more visible and promote exploration.
Click on the UIView , go to the identity inspector, and give the custom class the name BetterSegmentedControl for your UIView . Xcode will build your project so wait until the build finishes, then you have a custom segment on your UIView .
Enter Swift as Language and choose Next. Go to the Storyboard and drag a Segmented Control to the top of the main view. Also drag a Label to the view and place it below the Segmented Control. Select the label and give it a text of First Segment selected.
If I understand your question correctly, you simply have to implement a target-action method (supported by UIControl
which is UISegmentedControl
's parent class) for the constant UIControlEventValueChanged
, exactly like in the example given in UISegmentControl's reference documentation.
i.e.
[segmentedControl addTarget:self
action:@selector(action:)
forControlEvents:UIControlEventValueChanged];
used for a message with the following signature:
- (void)action:(id)sender
or
[segmentedControl addTarget:self
action:@selector(action:forEvent:)
forControlEvents:UIControlEventValueChanged];
for
- (void)action:(id)sender forEvent:(UIEvent *)event
or
[segmentedControl addTarget:self
action:@selector(action)
forControlEvents:UIControlEventValueChanged];
for the simplest method:
- (void)action
which are standard types of target-action selectors used in UIKit.
try this:
- (IBAction)segmentSwitch:(UISegmentedControl *)sender {
NSInteger selectedSegment = sender.selectedSegmentIndex;
if (selectedSegment == 0) {
}
else{
}
}
Simple version in swift updated
func loadControl(){
self.yourSegmentedControl.addTarget(self, action: #selector(segmentSelected(sender:)), forControlEvents: .valueChanged)
}
func segmentSelected(sender: UISegmentedControl)
{
let index = sender.selectedSegmentIndex
// Do what you want
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With