简体   繁体   中英

UISegmentedControl: Programmatically Set Index?

I'm trying to load a user setting into a segmented control. The NSUserDefault reads correctly, and the preference is correctly translated into an index. However, the segmented control does not seem to respond to setting the index, preferring to stay at index 0.

The code clean compiles with -Wall -Wextra , and clang does not report any issues. I've also run with both Leaks and Zombies - OK. And the ASSERTs below do not fire.

The UISegmentedControl were created using Interface Builder (there are 4 total on the view). I've verified the connections. I've tried calling -loadPreferences in -viewDidLoad , -viewWillAppear , and -viewDidAppear .

Are there any tricks I'm missing? Should I be calling a needsUpdate or some other method to get the controls to repaint?

Jeff

-(void)loadPreferences
{
   NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
   ...

    int days = [userDefaults integerForKey:kDirtyAfter];
    ASSERT(IsValidDirtyDays((DirtyDays)days));
    if(!IsValidDirtyDays((DirtyDays)days))
        days = (int)DirtyDaysDefault;

    int idx;
    switch(days)
    {
        case DirtyDays1: idx = 0; break;
        case DirtyDays3: idx = 1; break;
        case DirtyDays7: idx = 2; break;
        case DirtyDays14: idx = 3; break;
        case DirtyDays28: idx = 4; break;
        default: idx = 1;
    }

    // dirtyAfterSegment.selectedSegmentIndex = idx;
    [dirtyAfterSegment setSelectedSegmentIndex:idx];
    ASSERT(dirtyAfterSegment.selectedSegmentIndex == idx);
}

If the Assert does not fire, then something must be changing the index to 0 after this code, or the code itself is always using the first case statement.

Create an action on valueChanged for the segment, and set a breakpoint in that action to see when the segment is being changed and who is changing it.

You said you created the segmented controls in interface builder, did you create IBOutlets for them and connect them as well?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM