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

时间:2015-10-15 16:38:28

标签: swift user-interface tvos

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

1 个答案:

答案 0 :(得分:1)

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

  • 在这种情况下,分段控制是查看
  • 带有SegmentedControl的ViewController是控制器
  • 您必须为背景颜色创建模型

模型已更改并存储在选定的段UIControlEventValueChanged事件中。当控制器刷新视图时,“分段控制”选项由模型确定。

下面是一个例子,你如何做到这一点。作为模型,我决定使用BackgroundColorIndex翻译为selectedSegmentIndex。剪切利用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