众所周知,ViewController中button的单击事件为:
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
直接在该文件下面实现方法:
- (void):(UIButton *)btn
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"详细信息" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAler = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *cancelAler = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
[aler addAction:sureAler];
[aler addAction:cancelAler];
[self presentViewController:aler animated:YES completion:nil];
}
但是在TableView的cell中则会报错,无法调用presentViewController,因为cell页面继承自UITableViewCell,且设置时需要区分是来自哪个按钮的请求,故必须设置tag值
1、首先,在该cell的头文件里面设置自定义代理(代理名字AlertClickDelegate自拟),写在@interface前面
@protocol AlertClickDelegate <NSObject>
-(void)clickTest:(NSInteger *)tag;
@end
然后在@interface里面声明代理
@property (nonatomic,weak)id<AlertClickDelegate>alertDelegate;
2、在cell页面的单击方法中设置代理转跳,并声明代理方法(此处代理方法为clickTest)
- (void)click:(UIButton *)btn
{
if (self.alertDelegate != nil && [self.alertDelegate respondsToSelector:@selector(clickTest:)]) {
[self.alertDelegate clickTest:btn.tag];
}
}
3、在TableViewController里声明代理@interface后面写上
在cellForRow方法中,在声明并用到该自定义代理的cell中,设置代理cell.alertDelegate = self;
4、在TableViewController中,写入真正的单击事件具体方法
- (void)clickTest:(NSInteger *)tag
{
if (tag == 0) {
UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"详细信息" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAler = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *cancelAler = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
[aler addAction:sureAler];
[aler addAction:cancelAler];
[self presentViewController:aler animated:YES completion:nil];
}else if(tag == 1){
UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"详细信息" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAler = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *cancelAler = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
[aler addAction:sureAler];
[aler addAction:cancelAler];
[self presentViewController:aler animated:YES completion:nil];
}
}