簡體   English   中英

如何在iOS的TableView中僅選擇兩行?

[英]How to select only two rows in tableview in iOS?

我試圖在一次表格視圖中一次只允許選擇兩行,但是看來我收效不好!

想法是選擇一行,然后將對象發送到核心數據,然后選擇第二行,將另一件事發送到核心數據。 但是,如果選擇多於兩行,它將顯示一個警報視圖,提示您只能選擇兩行。

我已經試過了:

    NSArray *indexPathArray = [[NSArray alloc]init];
indexPathArray = [self.mainTableView indexPathsForSelectedRows];

if ( indexPathArray.count == 1) {
    NSLog(@"%@",@"we have 1 cell selected");
}
if ( indexPathArray.count == 2) {
    NSLog(@"%@",@"We have 2 cells selected!");
}
if (indexPathArray.count > 2) {
    NSLog(@"%@",@"ERROR ERROR!!!");
}

而且我嘗試了許多其他的Google和堆棧溢出建議,但並沒有結束!

那么我該如何實現呢?

這是我有代碼的方法:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath(NSIndexPath*)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];

[self setSelection:indexPath];
_profile = [self.fetchedResultsController objectAtIndexPath:indexPath];

NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
    rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
NSLog(@"%ld",(long)rowNumber);

NSArray *indexPathArray = [[NSArray alloc]init];
indexPathArray = [self.mainTableView indexPathsForSelectedRows];

if ( indexPathArray.count == 1) {
    NSLog(@"%@",@"we have 1 cell selected");
}
if ( indexPathArray.count == 2) {
    NSLog(@"%@",@"We have 2 cells selected!");
}
if (indexPathArray.count > 2) {
    NSLog(@"%@",@"ERROR ERROR!!!");
}
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];      }

刪除此行:

[tableView deselectRowAtIndexPath:indexPath animated:YES];

didSelectRowAtIndexPath:方法中。

在方法中的代碼中注釋/刪除以下幾行
-(void)tableView:(UITableView )tableView didSelectRowAtIndexPath(NSIndexPath )indexPath

[tableView deselectRowAtIndexPath:indexPath animated:YES];  
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

並檢查。 然后,您的邏輯部分應該可以正常工作。

說明:TableView方法indexPathsForSelectedRows將返回選定的行數。 您正在使用以下代碼行取消選擇選定的行:

[tableView deselectRowAtIndexPath:indexPath animated:YES];

僅注釋/刪除這一行代碼將使indexPathArray計數為1,因為您仍然可以使用以下方法在方法末尾重新加載行:

[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

上面的代碼還可以在重新加載該行時將其重置為未選擇狀態。 因此,您也需要評論或刪除它。

暫無
暫無

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

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