Dex*_*ter 1 iphone xcode objective-c
我有一个tableViewController,单元格包含一个按钮和一个标签.Person当用户点击按钮时,我需要获取单元格的文本(实际上是单元格的对象).
当用户点击按钮时,执行以下方法;
-(void) buttonOfCellClicked{
// here i need to access the `Person` object that the user clicked
}
Run Code Online (Sandbox Code Playgroud)
我该如何编写这段代码?
编辑:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Run Code Online (Sandbox Code Playgroud)
Person*person = [personsArr objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] ;
label = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 75, 60)];
label.text =person.firstName;
[cell addSubview:label];
UIButton *button= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(buttonOfCellClicked) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
}
Run Code Online (Sandbox Code Playgroud)
id findAncestor(UIView *view, Class class) {
while (view && ![view isKindOfClass:class])
view = [view superview];
return view;
}
- (void)buttonOfCellClicked:(UIButton *)button
{
UITableViewCell *cell = (UITableViewCell *)findAncestor(button, [UITableViewCell class]);
UITableView *table = (UITableView *)findAncestor(cell, [UITableView class]);
NSIndexPath *path = [table indexPathForCell:cell];
if (!path)
return;
Person *person = [personsArr objectAtIndex:path.row];
// do whatever with person
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
637 次 |
| 最近记录: |