2016-09-28 14 views
-3

我希望能夠選擇一行或多行,並通過IBAction執行某些操作。假設我有四行,A,B,C和D.如果我選擇A和B,然後按連接到該IBAction的按鈕,則會發生一些情況。使用IBAction(Obj-C)對UITableView中的選定行執行某些操作

我該如何解決這個問題?

代碼:

@implementation ViewController { 

NSArray *names; 

} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

{ 

return [names count]; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

{ 

static NSString *tableIdentifier = @"tableCell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier]; 

if (cell == nil) { 

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier]; 

} 

cell.textLabel.text = [names objectAtIndex:indexPath.row]; 
return cell; 

} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

if ((indexPath.row == 0) && (indexPath.row == 2)) { 

    NSLog(@"John and James selected."); 

} 


} 

- (void)viewDidLoad { 

[super viewDidLoad]; 
// Initialize table data 
names = [NSArray arrayWithObjects:@"John", @"Michael", @"Hannah", @"James", nil]; 

} 

謝謝!

+0

按「IBAction」是什麼意思? –

+0

@SatishMavani我的意思是按鈕,對不起。連接到該IBAction的按鈕! – Yomo

+0

你想要選擇多行嗎? –

回答

1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; 

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) { 
     [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark]; 
     [selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]]; 
    } else { 
     [selectedCell setAccessoryType:UITableViewCellAccessoryNone]; 
     [selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]]; 
    } 

    [tableView deselectRowAtIndexPath:indexPath animated:NO]; 

} 

此代碼將在您選擇的行上顯示刻度線。

您還必須使用映射已檢查的單元格的數組,並且必須在cellForRowAtIndexPath中驗證是否應該檢查accessoryType。

然後在你的按鈕動作,你可以做你的代碼與選定的行。

希望這會有所幫助!

+0

我添加了代碼,請幫忙。我只能選擇一行,我想選擇多個! – Yomo

+1

我編輯的代碼只使用這一個! –

+0

我還沒有宣佈selectedCell? – Yomo

相關問題