ios - 如何在 UIAlertController 中添加 UIImageView?

标签 ios objective-c uiimageview uialertcontroller

我希望 UIAlertControllerActionSheet 中使用 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];

最佳答案

您可以通过子类化 UIAlertController 并将 \n 添加到标题字符串来为 UIImageView 腾出空间,从而在标题标签上方添加图像.您必须根据字体大小计算布局。对于 UIAlertAction 中的图像,请像这样使用 KVC:self.setValue(image, forKey: "image")。我建议使用检查 responds(to:) 的扩展。

Here is sample implementation.

enter image description here

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"
    }
}

关于ios - 如何在 UIAlertController 中添加 UIImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37848224/

相关文章:

iOS 动画 clipToBounds、masksToBounds 或类似的

ios - 如何在 iOS 中以编程方式绘制到显示屏?

iphone - UISegmentedControl 抛出异常

ios - Swift - 在编辑模式下更改表格单元格背景

ios - 自定义 UITableViewCell - 不显示

ios - NSURLCacheStoragePolicy请求与响应

ios - 如何在 GMSMapView 中创建地理围栏?

iphone - MapKit iPhone 显示缩放控件

ios - 如何删除子层cocos2d

interface-builder - 苹果界面生成器 : adding subview to UIImageView