如何在UIAlertController中添加UIImageView?

我想UIAlertController目前与ActionSheet中的UIImageView警报。 但是当我运行的应用程序,然后是终止….

这是我的代码:

 UIAlertController * alert= [UIAlertController alertControllerWithTitle:@"Title" message:@"Welcome" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* okButton = [UIAlertAction actionWithTitle:OK style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }]; [alert addAction:okButton]; UIImageView *imgv=[[UIImageView alloc]initWithFrame:CGRectMake(20,20,50,50)]; imgv.image=[UIImage imageNamed:@"kaga.jpg"]; [alert setValue:imgv forKey:@"image"]; [self presentViewController:alert animated:YES completion:nil]; 

根据Apple Doc,无法将图像添加到UIAlertController

如果你想,那么你可以创build自己的自定义视图,如:

https://github.com/wimagguc/ios-custom-alertview

如果你想把图像显示在button然后尝试像这样:

 UIAlertController * alert= [UIAlertController alertControllerWithTitle:@"Title" message:@"Welcome" preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction* okButton = [UIAlertAction actionWithTitle:OK style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { //Do some thing here [alert dismissViewControllerAnimated:YES completion:nil]; }]; [okButton setValue:[[UIImage imageNamed:@"kaga.jpg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; [alert addAction:okButton]; [self presentViewController:alert animated:YES completion:nil]; 

您可以通过UIAlertController并在标题string中添加\n来为UIImageView创build空间,从而在标题标签上添加图像。 你必须根据字体大小来计算布局。 对于使用KVC UIAlertAction self.setValue(image, forKey: "image")self.setValue(image, forKey: "image") 。 我会build议扩展,检查responds(to:) 。 这里是示例实现。 在这里输入图像说明

 extension UIAlertAction { /// Image to display left of the action title var actionImage: UIImage? { get { if self.responds(to: Selector(Constants.imageKey)) { return self.value(forKey: Constants.imageKey) as? UIImage } return nil } set { if self.responds(to: Selector(Constants.imageKey)) { self.setValue(newValue, forKey: Constants.imageKey) } } } private struct Constants { static var imageKey = "image" } } 

你应该设置button的图像不警报。