2011-05-07 107 views
16

我想知道是否有一種方法可以讓我的代碼在我的UITableView中「點擊」一個單元格,以便重現- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath委託方法中指定的行爲。如何以編程方式「點擊」UITableView單元格?

我想換句話說,是可以以編程方式調用- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath委託方法嗎?

回答

19

難道你不能把didSelectRowAtIndexPath中的任何邏輯放到一個單獨的方法中,只需從didSelectRowAtIndexPath和其他任何你想調用相同代碼的地方調用該方法?

+0

謝謝,這實際上是我做了什麼,我的作品... – cgossain 2011-05-07 02:16:20

+1

是的,但單元格不像突出顯示時那樣突出顯示。那裏有任何想法? – 2015-01-31 16:29:28

+1

@BeemerFan:只需從調用新的常用方法的方法調用:[self.tableView selectRowAtIndexPath:myIndexPath animated:false scrollPosition:UITableViewScrollPositionNone]; – Rob 2015-09-30 15:05:48

0

這只是一種方法。繼續,像調用任何其他方法一樣調用它。

+4

這實際上是一個實例方法,而不是一個類的方法 - 但是,嘿,這可能是吹毛求疵:d。 – Till 2013-03-18 23:04:27

35

,如果你想擁有小區選擇,即突出一個特定的細胞:

//select first row of first section 
NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0]; 
[self.tableView selectRowAtIndexPath:selectedCellIndexPath animated:false scrollPosition:UITableViewScrollPositionMiddle]; 

,如果你想在你的didSelectRowAtIndexPath方法的方法來另外觸發動作,你需要手動調用委託方法,它贏得了」自動發生:

[self tableView:self.tableView didSelectRowAtIndexPath:selectedCellIndexPath]; 
+0

第二行代碼爲我完成了工作,謝謝。 – 2012-12-18 14:36:24

+0

雖然調用didSelectRowAtIndexPath不會觸發segues。 – Andy 2015-03-01 14:16:26

+0

是的。適用於我。 – Tander 2015-04-24 09:07:36

0

這是一個6.1更新。當你使用segues時,所有的建議都很好,但你也必須調用segue。所以 - 要添加到建議和總結它

// ... assuming we just added a new row - which is one use of what this thread is trying to do 

/* get new count - this is the row we are going to highlight - 0 based */ 
int newIndex = [dataArrayUnderlyingTable count]-1; 

/* make it look pretty by highlighting it */ 
    NSIndexPath *nip = [NSIndexPath indexPathForRow:newIndex inSection:0]; 
    [[self tableView] selectRowAtIndexPath:nip animated:YES scrollPosition:UITableViewScrollPositionBottom]; 

/* run the code in the following method so it is not missed */ 
    [self tableView:[self tableView] didSelectRowAtIndexPath:nip]; 

/* now 'tap' on it ... or simulate it */ 
    [self performSegueWithIdentifier: @"viewChildDetails" sender: self]; 
1

雨燕3.2解決方案

let indexPath = IndexPath(row: 2, section: 0) // change row and section according to you 
tblView.selectRow(at: indexPath, animated: true) 
tblView.delegate?.tableView!(tblView, didSelectRowAt: indexPath) 
+0

似乎這是採取在這裏https://stackoverflow.com/a/40590050/5790492! – 2017-10-20 13:50:01

相關問題