在 tvOS 中更改视图时如何保持选择的段?

How to keep the segment chosen when change view in tvOS?

我在 tvOS 应用程序中有一个分段控件,用于选择主视图的背景。不幸的是,每次我更改视图并返回主视图时,所选片段都会丢失,并且控件会重置为默认选项。保留用户选择的最佳方式是什么?

MVC(模型-视图-控制器)模式是解决方案。

  • 在这种情况下分段控件是 视图
  • 带有 SegmentedControl 的 ViewController 是一个 Controller
  • 您必须为背景颜色创建一个 模型

模型根据选定的段 UIControlEventValueChanged 事件更改并存储。 Segmented Control选择是由Controller刷新View时的Model决定的。

下面是一个例子,你可以如何做到这一点。作为模特我决定使用BackgroundColorIndex翻译to/fromselectedSegmentIndex。 snipped 利用 NSUserDefaults 存储模型,并在控制器从模型读取时确定背景颜色和索引。

#import "ViewController.h"

typedef NS_ENUM(NSUInteger, BackgroundColorIndex) {
    BackgroundColorIndexBlack = 0,
    BackgroundColorIndexBlue,
    BackgroundColorIndexGreen,
};

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedControl;
@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // restore & set previously stored state
    [self restoreState];
    [self changeBackgroundColorWithIndex:self.segmentedControl.selectedSegmentIndex];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // the code from viewWillAppear: could be here, but I don't know specifycally
    // what flow do you have and what method is appropriate to handle selected segment change action
}

- (IBAction)segmentedControlDidChangeValue:(id)sender {
    if ([sender isEqual:self.segmentedControl]) {
        // change & save current state
        [self changeBackgroundColorWithIndex:self.segmentedControl.selectedSegmentIndex];
        [self saveState];
    }
}

- (void)saveState
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@(self.segmentedControl.selectedSegmentIndex) forKey:@"colorIndex"];
    [defaults synchronize];
}

- (void)restoreState
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    id storedObj = [defaults objectForKey:@"colorIndex"];
    if (storedObj) {
        NSInteger index = [(NSNumber *)storedObj integerValue];
        self.segmentedControl.selectedSegmentIndex = index;
    }
    else {
        // first launch state
        self.segmentedControl.selectedSegmentIndex = 0;
    }
}

- (void)changeBackgroundColorWithIndex:(BackgroundColorIndex)colorIndex
{
    switch (colorIndex) {
        case BackgroundColorIndexBlack: {
            self.view.backgroundColor = [UIColor blackColor];
        } break;
        case BackgroundColorIndexBlue: {
            self.view.backgroundColor = [UIColor blueColor];
        } break;
        case BackgroundColorIndexGreen: {
            self.view.backgroundColor = [UIColor greenColor];
        } break;
        default:
            break;
    }
}
@end