我已经在 Swift 中看到了这个问题的解决方案。谁能帮帮我?
我在 TableViewController 类中有这个方法:
- (void)presentAlert {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Flag Content"
message:@"Are you sure you want to report this post?"
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"OK", @"OK action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(@"OK action");
[cell.feedItem incrementKey:@"flagTotal"];
[cell.feedItem saveInBackground];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:cell.flagButton cache:YES];
[UIView commitAnimations];
// Set flagButton image to checked image
[cell.flagButton setImage:[UIImage imageNamed:@"filledFlagButtonIcon"] forState:UIControlStateNormal];
[self dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
preferredStyle:UIAlertControllerStyleAlert];
我曾希望简单地从单元格中的 IBAction 中调用此方法,例如:
- (IBAction)flagTapped:(id)sender {
_tableView = [[FeedTableViewController alloc] init];
[_tableView presentAlert];
}
最佳答案
这不是正确的做法。您可以通过两种方式实现这一目标。一种方法是在您的 cellForRowAtIndexPath 中添加目标操作并从您的单元格类中删除 - (IBAction)flagTapped:(id)sender
并从界面构建器中的单元格中删除它的操作,因为我们正在以编程方式进行操作,例如:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
[cell.button addTarget:self action:@selector(presentAlert) forControlEvents:UIControlEventTouchUpInside];
}
实现此目的的另一种方法是在您的单元类中定义一个协议(protocol)。在该协议(protocol)中添加此方法 - (void)presentAlert 声明。将 TableViewController 设置为 cellForRowAtIndexPath 中单元格的委托(delegate)。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
cell.delegate = self;
}
flagTapped 的实现是这样的
- (IBAction)flagTapped:(id)sender {
[self.delegate presentAlert];
}
关于ios - 从 TableViewCell 中显示 AlertController,Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207730/