[英]Show AlertController from TableViewCell, Objective-C
I've seen solutions to this problem in Swift. 我已经在Swift中看到了解决此问题的方法。 Can anyone help me out? 谁能帮我吗?
I have this method in the TableViewController class: 我在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];
I had hoped to simply call this method from the IBAction in the cell like: 我曾希望简单地从单元格中的IBAction调用此方法,例如:
- (IBAction)flagTapped:(id)sender {
_tableView = [[FeedTableViewController alloc] init];
[_tableView presentAlert];
}
This is not the right approach of doing this. 这不是正确的方法。 You can achieve this in two ways. 您可以通过两种方式实现这一目标。 One way is add target action in your cellForRowAtIndexPath and remove - (IBAction)flagTapped:(id)sender
from your cell class and also remove its action from cell in interface builder as we are doing it programmatically like: 一种方法是在cellForRowAtIndexPath中添加目标操作,并从单元格类中删除- (IBAction)flagTapped:(id)sender
,并在接口构建器中从程序单元格中删除其操作,就像我们以编程方式进行操作一样:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
[cell.button addTarget:self action:@selector(presentAlert) forControlEvents:UIControlEventTouchUpInside];
}
Another way of achieving this is define a protocol in your cell class. 实现此目的的另一种方法是在您的单元格类中定义一个协议。 Add this method - (void)presentAlert declaration in that protocol. 在该协议中添加此方法-(void)presentAlert声明。 Set TableViewController as delegate of cell in cellForRowAtIndexPath as. 将TableViewController设置为cellForRowAtIndexPath中的单元格委托。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
cell.delegate = self;
}
Implementation of flagTapped will be like flagTapped的实现将像
- (IBAction)flagTapped:(id)sender {
[self.delegate presentAlert];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.