【问题标题】:How to let the user reorder sections in a UITableView如何让用户重新排序 UITableView 中的部分
【发布时间】:2014-07-03 23:44:05
【问题描述】:

我正在开发一个包含股票的应用程序,按投资组合排列。所以这很适合表格视图,我正在处理编辑交互;允许用户添加或删除股票,将它们拖到一个投资组合中或另一个投资组合中,这很简单,但我无法优雅地做的一件事是让用户将一个投资组合拖到另一个投资组合的上方或下方。

我现在有一个 hacky 解决方案,其中每个部分的第 0 行是投资组合名称,如果他们将该行拖到另一个投资组合上方,整个表格会重新加载并切换投资组合。这可行,但感觉不是很自然。

我确定我不是第一个遇到这个问题的人;谁有更完善的解决方案?

一个相关问题 - 我如何让用户创建一个新的投资组合/部分?

【问题讨论】:

  • 如果我的回答符合您的要求,请接受。否则,请告诉我。

标签: ios uitableview


【解决方案1】:

简单易懂:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSMutableArray *_data;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _data = [NSMutableArray arrayWithObjects:@"One", @"Two", @"Three", nil];
    self.tableView.editing = YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"reuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:identifier];
    }
    cell.textLabel.text = _data[indexPath.row];
    cell.showsReorderControl = YES;

    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    [_data exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
}

@end

编辑:

你现在问的有点复杂。我创建了一个将表格放入单元格的示例,它为您提供了嵌套单元格。这个例子很不吸引人,但它很有效,你没有理由不能让它看起来很漂亮,所以看看吧:

https://github.com/MichaelSnowden/TableViewInCell

如果这对您不起作用,请尝试让 UITableView moveSection:(NSInteger) toSection:(NSInteger) 看起来更漂亮。 Documentation for that method is here.

我对上述方法的体验是,它非常好用,调用时看起来也不错。使用它的一种聪明方法是使用轻击手势识别器创建标题。在第一次点击时,突出显示该部分并记录该 indexPath,然后在第二次点击时,在两个索引路径上调用方法。它应该可以很好地工作,但您不会从中拖放。

【讨论】:

  • 这看起来很好,但我的问题是关于重新排列部分。在一个部分内重新排列行或在部分之间移动它们都可以正常工作。
  • @Apollo 然后将表格视图放入每个单元格中。
  • @Apollo 我添加了一个示例项目
猜你喜欢
  • 1970-01-01
  • 2018-10-27
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多