我有一个子类UITableViewCell,每个单元格上都有一个“开始”和“完成”按钮。按“开始”后会创建“完成”按钮。如果我在我的子类UITableViewCell文件中按下按钮逻辑,则触发就好了。
但是我知道我实际上想要按下按钮来触发表视图中的编辑模式,所以我想在我的cellForRowAtIndexPath而不是子类文件中有一些逻辑。但后来我无法触发按钮:(
我做错了什么或不理解?
我的TableViewCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self.startButton = [[UIButton alloc] initWithFrame:CGRectMake(250 + 0.60 * self.screenWidth, 65, 150, 30)];
[self.startButton addTarget:self action:@selector(onStartButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
self.startButton.backgroundColor = [UIColor colorWithRed:0.16 green:0.65 blue:0.19 alpha:1.0];
btnLayer = [self.startButton layer];
[btnLayer setMasksToBounds:YES];
[btnLayer setCornerRadius:5.0f];
[self.startButton setTag:1];
[self addSubview:self.startButton];
}
- (void)onStartButtonPressed:(id)sender {
if (self.countdown)
{
[self beginDoneButton];
}
}
-(void)beginDoneButton {
self.startButton.enabled = NO;
self.startButton.hidden = YES;
self.doneButton = [[UIButton alloc] initWithFrame:CGRectMake(250 + 0.60 * self.screenWidth, 65, 150, 30)];
self.doneButton.backgroundColor = [UIColor colorWithRed:0.16 green:0.65 blue:0.19 alpha:1.0];
CALayer *btnLayer = [self.doneButton layer];
[btnLayer setMasksToBounds:YES];
[btnLayer setCornerRadius:5.0f];
[self.doneButton setTitle:@"Done "forState:UIControlStateNormal];
[self addSubview:self.doneButton];
}
我的TableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// get index of Data
int index = (int) indexPath.row;
id order = [orders objectAtIndex:index];
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
cell = [[OrderTableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:@"orderCell"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.customerNameLabel.text = [order objectForKey:@"first_name"];
cell.orderLabel.text = [NSString stringWithFormat: @"Order #%@", [order objectForKey:@"order_id"]];
[cell.customerImageView sd_setImageWithURL:[NSURL URLWithString: [order objectForKey:@"profile_image"]]
placeholderImage:[UIImage imageNamed:@"stub"]
];
[cell.messageButton setTitle:@"Message" forState:UIControlStateNormal];
// This doesn't work
[cell.doneButton addTarget:self action:@selector(onDoneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
// This doesn't get fired
- (IBAction)onDoneButtonPressed:(id)sender {
NSLog(@"pressed");
UITableViewCell *cell = (UITableViewCell *)[sender superview];
NSIndexPath *pathToCell = [self.tv indexPathForCell:cell];
}
答案 0 :(得分:0)
这个怎么样:
在自定义表格视图单元格中,创建按钮但不要向其添加目标/操作只需将它们连接到单元格类中的IBOutlet。
然后在您的cellForRowAtIndexPath中,将单元格指针强制转换为自定义单元格类,并使用cell.button1Outlet出口在视图控制器作为目标的按钮上设置目标/操作。现在,您的单元格按钮将调用视图控制器中的方法,而不是单元格中的方法,即使插座属于单元格。