我希望 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];
最佳答案
您可以通过子类化 UIAlertController
并将 \n
添加到标题字符串来为 UIImageView
腾出空间,从而在标题标签上方添加图像.您必须根据字体大小计算布局。对于 UIAlertAction
中的图像,请像这样使用 KVC
:self.setValue(image, forKey: "image")
。我建议使用检查 responds(to:)
的扩展。
Here is sample implementation.
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/