我遇到了同样的问题,我通过将单元格子类化到它自己的类中来解决它,并将按钮作为插座放在那里,并用模型中的数据填充单元格,同时使用返回我们当前正在查看的单元格的方法.
例如,如果您有一个 Person 类,并且每个人都有一个名字、一个姓氏和一些朋友。每次单击单元格中的按钮时,特定人的朋友数量就会增加 1。
_______________DATA SOURCE___________________________
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *comment;
@property (nonatomic) NSInteger numberOfFriends;
+(instancetype)personWithName:(NSString *)aName Surname:(NSString *)aSurname;
@end
#import "Person.h"
@implementation Person
+(instancetype)personWithName:(NSString *)aName Surname:(NSString *)aSurname{
Person *person = [[Person alloc] init];
[person setName:aName];
[person setSurname:aSurname];
[person setNumberOfFriends:0];
return person;
}
@end
_____________________PERSON CELL________________________
#import <UIKit/UIKit.h>
@interface PersonCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *friendsNum;
@property (strong, nonatomic) IBOutlet UIButton *friendsBtn;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *surnameLabel;
@end
我个人创建了一个私有 NSArray 来保存我的 Person 对象的名称,以及一个私有 NSMutableDictionary 来保存我的 Person 对象,并且我将键设置为人名。
_____________________PERSON TABLE VIEW________________________
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
PersonCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *name = [peopleNames objectAtIndex:indexPath.row];
Person *person = [people objectForKey:name];
if(cell == nil)
{
cell = [[PersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.nameLabel.text = person.name;
cell.surname.Label.text = person.surname
[cell.friendsButton addTarget:self action:@selector(moreFriends:) forControlEvents:UIControlEventTouchUpInside];
cell.friendsNum.text = [NSString stringWithFormat:@"%i", person.numberOfFriends];
return cell;
}
- (IBAction)moreFriends:(id)sender {
UIButton *btn = (UIButton *)sender;
PersonCell *cell = [self parentCellForView:btn];
Person *person = [people objectForKey:cell.nameLabel.text];
person.numberOfFriends++;
[self.tableView reloadData];
}
-(PersonCell *)parentCellForView:(id)theView
{
id viewSuperView = [theView superview];
while (viewSuperView != nil) {
if ([viewSuperView isKindOfClass:[PersonCell class]]) {
return (PersonCell *)viewSuperView;
}
else {
viewSuperView = [viewSuperView superview];
}
}
return nil;
}