转到您的 CustomCell.h 并在 #import 正下方添加此代码。
@protocol CustomCellDelegate <NSObject>
- (void)buttonActionwith :(NSIndexPath *)indexPath;
@end
然后在@interface CustomCell 正下方添加此代码:UITableViewCell
//Manual Properties
@property (strong, nonatomic) NSIndexPath *buttonIndexPath;
//Delegate
@property (nonatomic, weak) id <CustomCellDelegate> delegate;
这个 NSIndexPath 的用途是识别用户选择了哪个单元格。
然后转到 CustomCell.m 并在您的按钮 IBAction 方法中添加此代码。
[self.delegate buttonActionwith:self.buttonIndexPath];
这行代码的意思是,当用户TouchUpInside Button在cell buttonActionwith委托方法调用时,如果你在UITableView所在的UIViewController中设置了这个CustomCellDelegate,那个委托方法也会在那个ViewController里面调用。
现在转到您的 MainViewController.h 并添加
自定义CellDelegate
& 之后会是这个样子,
@interface MainViewController : UIViewController <CustomCellDelegate,,UITableViewDataSource,UITableViewDelegate>
在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath创建自定义UITableViewCell时别忘了在return cell前加上这行代码;
//Set Cell Values Here
cell.delegate = self; //Setting delegate to self
cell.buttonIndexPath = indexPath;
修改后的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath会是这个样子,
static NSString *MyIdentifier = @"MyIdentifier"; //Set Identifier for cell
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier]; //init CustomCell
if (cell == nil) { //Check cell is nill or not
NSArray *nib;
nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"
owner:self options:nil]; //if cell is nil add CustomCell Xib
for (id oneObject in nib) if ([oneObject isKindOfClass:[CustomCell class]])
cell = (CustomCell *)oneObject;
}
//Set Cell Values Here
cell.buttonIndexPath = indexPath
return cell;
最后在 MainViewController.m 中添加这个方法
#pragma mark - SwipeableCellDelegate
- (void)buttonActionwith:(NSIndexPath *)indexPath { //Delegate method
NSLog(@"Button Clicks at index %ld",(long)indexPath.row);
}
这是在单元格内添加单个按钮的方法。您可以使用此方法为单元格添加更多按钮。