簡體   English   中英

用代碼中的靜態單元格重新排列UITableview

[英]Reorder UITableview with static cells in Code

我有一個帶有7個靜態單元格的UITableview,每個單元格都有一個到另一個視圖的序號。 我想使單元可以重新排序。 用戶將單元重新排序后,我正在將每個單元的復用ID和位置寫入NSUserdefaults中。

但是我怎樣才能告訴Tableview當(重新)加載視圖時需要在哪顯示Cell。

最好的祝福

短劍

通常,在使用靜態表視圖時,您不會實現數據源方法,但在這種情況下,似乎有必要這樣做。 我創建了一個IBOutletCollection,並將我的單元格添加到了該數組中(我按從第一個單元格到最后一個單元格的順序添加了它們,因此它們將在表第一次加載時出現在情節提要中)。 在cellForRowAtIndexPath中,您不能使單元出隊,因為這不適用於靜態單元,因此,我從插座集合中獲取了該單元。 我有一個單獨的數組,用於跟蹤單元格應出現的順序,這就是我保存到用戶默認設置的內容。 這是在我的測試中起作用的代碼,

@interface StaticTableViewController ()
@property (strong,nonatomic) NSMutableArray *cells;
@property (strong, nonatomic) IBOutletCollection(UITableViewCell) NSArray *tableCells;

@end

@implementation StaticTableViewController

-(void)viewDidLoad {
    [super viewDidLoad];
    self.cells = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"cells"] mutableCopy];
    if (! self.cells) self.cells = [@[@0,@1,@2,@3,@4] mutableCopy];
}



- (IBAction)enableReordering:(UIBarButtonItem *)sender {
    [self.tableView setEditing:YES animated:YES];
}


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


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger idx = [self.cells[indexPath.row] integerValue];
    UITableViewCell *cell = self.tableCells[idx];
    return cell;
}



-(BOOL)tableView:(UITableView *)tableview shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}


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


- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    NSNumber *numberToMove = self.cells[fromIndexPath.row];
    [self.cells removeObjectAtIndex:fromIndexPath.row];
    [self.cells insertObject:numberToMove atIndex:toIndexPath.row];
    [[NSUserDefaults standardUserDefaults] setObject:self.cells forKey:@"cells"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM