UISegmentedControl selected index always 0?

给你一囗甜甜゛ 提交于 2020-01-14 09:22:12

问题


I have a UISegmentedControl that has 6 segments which I created in Interface Builder. I am calling the following method on value changed:

-(IBAction)segmentedChartButtonChanged:(id)sender
{
    switch (self.segmentedChartButton.selectedSegmentIndex) {
        case 0:
            NSLog(@"5d selected. Index: %d", self.segmentedChartButton.selectedSegmentIndex);
            break;
        case 1:
            NSLog(@"3m selected. Index: %d", self.segmentedChartButton.selectedSegmentIndex);
            break;
        default:
            break;
    }
}

Whenever I change the segments, the selectedSegmentIndex is always 0. Why is this?


回答1:


It is very likely that the IBOutlet isn't connected. Check that. You can also use the sender that is passed to the method.

UISegmentedControl * segmentedControl = (UISegmentedControl *)sender;
switch (segmentedControl.selectedSegmentIndex) {
    ....



回答2:


hi try like this it will work

-(IBAction)segmentedChartButtonChanged:(id)sender
 {
 UISegmentedControl *segment=(UISegmentedControl*)sender;
switch (segment.selectedSegmentIndex) {
    case 0:
        NSLog(@"5d selected. Index: %d", self.segmentedChartButton.selectedSegmentIndex);
        break;
    case 1:
        NSLog(@"3m selected. Index: %d", self.segmentedChartButton.selectedSegmentIndex);
        break;
    default:
        break;
}

}




回答3:


Take an outlet for UISegmentedControl and handle with that like this,

if (self.paymentSegmentButton.selectedSegmentIndex ==0)
{
    NSLog(@"first view ");

}
else
{
    NSLog(@"payment initiation");
    addVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"secondView"];

    [self.navigationController pushViewController:addVC animated:YES];

       }

I hope it helps someone.



来源:https://stackoverflow.com/questions/6585896/uisegmentedcontrol-selected-index-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!