[英]Can't select table view cell programmatically
I have a custom UITableViewCell
(MyCell) that contains a UIButton
and another custom cell. 我有一个自定义
UITableViewCell
(MyCell),其中包含一个UIButton
和另一个自定义单元格。 I would like to select the the cell programatically whose UIButton
has been tapped by the user. 我想以编程方式选择用户已点击其
UIButton
的单元格。 Actually I can call methods at button taps, but can't select the cell. 实际上,我可以在单击按钮时调用方法,但是无法选择单元格。 What did I missed?
我错过了什么? It doesn't crash, it runs, but this code doesn't make any changes except the NSLog.
它不会崩溃,它会运行,但是除了NSLog之外,此代码不会进行任何更改。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([object[@"num"] isEqualToString:@"one"]) {
MyCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
//... cell display
cell.acceptLabel.tag = indexPath.row;
[cell.acceptLabel addTarget:self action:@selector(didTapBttn:) forControlEvents:UIControlEventTouchUpInside];
return cell;
} else {
MyCustomTableViewCellB *cellMessage = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
//... cell display
return cellMessage;
}
}
//1. version
- (void)didTapBttn:(id)sender {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:
UITableViewScrollPositionNone];
NSLog(@"button tapped");
}
// 2. version
- (void)didTapBttn:(id)sender {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:indexPath];
NSLog(@"button tapped");
}
Why don't you inside the cell set 你为什么不进入电池组
-(void)awakeFromNib
{
//other code...
self.button.userInteractionEnabled = NO;
}
The tap will be passed to the cell via responder chain. 点击将通过响应者链传递到单元。
Well, assuming that you made sure that cell.acceptLabel
is a UIButton (weird name for a button) and that the if statement is true in your case: Then there is left to say that your first version should be right, except that you use the wrong indexPath. 好吧,假设您确保
cell.acceptLabel
是一个UIButton(按钮的怪异名称),并且if语句在您的情况下为true:那么剩下的就是您的第一个版本应该是正确的,除了您使用错误的indexPath。 You did assign the cell's indexPath.row as the button's tag (very good). 您确实将单元格的indexPath.row分配为按钮的标签(非常好)。 But why don't you use it then?
但是,为什么不使用它呢?
- (void)didTapBttn:(id)sender {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:((UIButton *)sender).tag inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
NSLog(@"button tapped");
}
Try this :) 尝试这个 :)
PS: You should still reconsider the sense behind your approach, though. PS:尽管如此,您仍然应该重新考虑方法的含义。 Selecting a tableview cell is typically done by tapping a cell.
通常通过点击一个单元格来选择一个tableview单元格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.