在XCode 4中使用AlertView对TableView单元格进行排序

时间:2012-07-12 02:11:45

标签: iphone xcode sorting tableview uialertview

我在NavigationBar中添加了一个“排序”按钮来对TableView进行排序。 TableView以这种方式构建:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *myfile = [[NSBundle mainBundle]
                    pathForResource:@"Object" ofType:@"plist"];

    sortedObjectes = [[NSMutableArray alloc]initWithContentsOfFile:myfile];

    NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"Popularity" ascending:YES];
    [sortedObjects sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
    [super viewDidLoad];
 }

这是排序按钮的操作:

- (IBAction)SortButton:(id)sender;

{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sort by" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Name", @"Country", @"Popularity", nil];                                                                                                                                   
[alert show];
[alert release];
}

这是抓住按钮点击的委托方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
    //Sort by name
    }
    else if (buttonIndex == 1)
    {
    //Sort by country
    }
    else if (buttonIndex == 2)
    {
    //Sort by popularity
    }
}

如何在ClickedButtonAtIndex中实现SortDescriptor方法,并更新TableView?

我希望tableview默认按人气排序。

Plist结构(字典数组):

plist version="1.0">
array>
    dict>
    key>Country /key>
    string>Italy /string>
    key>Name /key>
    string>Fezzudo /string>
            key>Popularity /key>
            integer>1 /integer>
        /dict>
   dict>
    key>Country /key>
    string>Spanin /string>
    key>Name /key>
    string>Alamos Malbec /string>
            key>Popularity /key>
            integer>2 /integer>
       /dict>
/array>
/plist>

不得不删除html代码的开头才能显示..它看起来像一团糟所以我想有人知道如何为我修复它..

2 个答案:

答案 0 :(得分:1)

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSSortDescriptor *sortDesc;
switch (buttonIndex) {
    case 0:
        return;
        break;
    case 1:
        sortDesc = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
        break;
    case 2:
        sortDesc = [[NSSortDescriptor alloc] initWithKey:@"Country" ascending:YES];
        break;
    case 3:
        sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"Popularity" ascending:NO comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
        break;
    }
    [sortedObjects sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
    [self.tableView reloadData];
}

答案 1 :(得分:0)

要显示2个以上的按钮(选项),最好使用UIACtionSheet而不是UIAlertView。操作表对我来说更好,因为我在弹出菜单中最多需要10个按钮。