如何在 UISearchBar 中保存选定的范围按钮?

How can I save selected scope button in UISearchBar?

我有一个带有 4 个范围按钮的 UISearchBar。我需要在下一次用户 select 另一个用户 objective C 中存储按下的范围按钮。有什么想法吗?

已解决: 这是其他人的解决方案

static NSString *yourKey = @"savedScopeSelection";

viewDidLoad

- (void)viewDidLoad
{

NSInteger newIndex = [[NSUserDefaults standardUserDefaults] integerForKey:yourKey];
[self.searchDisplayController.searchBar setSelectedScopeButtonIndex:newIndex];

}

UISearchBar 范围

    - (void)searchForText:(NSString *)searchText scope:(UYLWorldFactsSearchScope)scopeOption
{

    if (self.managedObjectContext)
    {

        NSString *predicateFormat = @"%K contains[cd] %@";
        NSString *searchAttribute = @"option0";
         [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:yourKey];
        if (scopeOption == searchScopeOption1)

        {
            searchAttribute = @"option1";
             [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:yourKey];
        }

        if (scopeOption == searchScopeOption2)
        {
            searchAttribute = @"option2";
             [[NSUserDefaults standardUserDefaults] setInteger:2 forKey:yourKey];
        }

        if (scopeOption == searchScopeOption3)
        {
            searchAttribute = @"option3";
             [[NSUserDefaults standardUserDefaults] setInteger:3 forKey:yourKey];
        }

        if (scopeOption == searchScopeOption4)
        {
            searchAttribute = @"option4";
             [[NSUserDefaults standardUserDefaults] setInteger:4 forKey:yourKey];

        }

        NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, searchAttribute, searchText];
        [self.searchFetchRequest setPredicate:predicate];

        NSError *error = nil;
        self.filteredList = [self.managedObjectContext executeFetchRequest:self.searchFetchRequest error:&error];
        if (error)
        {
            NSLog(@"searchFetchRequest failed: %@",[error localizedDescription]);
        }
    }
}

这似乎是使用 NSUserDefaults 的好时机。

在某处设置静态密钥

static NSString *yourKey = @"savedScopeSelection";

当您进行选择时,存储您选择的索引值:

 [[NSUserDefaults standardUserDefaults] setInteger:newIndexValue forKey:yourKey];

初始化搜索栏时,查看默认值以获取存储的索引:

  NSInteger *newIndex = [[NSUserDefaults standardUserDefaults] integerForKey:yourKey];

我建议您让每个范围按钮都用一个整数表示。您可以使用这样的枚举:

enum ScopeButtonIndex: Int {
    case thisScope = 1
    case thatScope = 2
    case otherScope = 3
    case fourthScope = 4
}

我喜欢专门给它一个索引,因为我将它存储在 userDefaults 中,而且我不想在将来的某个版本中通过添加另一个值来意外更改索引值