ios - 如何在 Swift 的 UIAlertView 中调整附件 View 的大小

标签 ios swift uialertview

我正在尝试在警报 View 中显示图像并使用以下代码:

let alertView = UIAlertView(title: "Alert", message: "Alert + Image", delegate: nil, cancelButtonTitle: "OK")
let imvImage = UIImageView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
imvImage.contentMode = UIViewContentMode.ScaleAspectFit
imvImage.image = objModelClass.creatorImage

//   alertView.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
alertView.setValue(imvImage, forKey: "accessoryView")

alertView.show()

问题是即使图像大小正确,而不是像 enter desciption image 这样的警报 View

最佳答案

Side note: UIAlertView is deprecated. UIAlertController is the current way to manage alerts.


这很有趣。无需在代码中指定图像大小。图像按原样表示,即图像的真实大小。

在测试中,UIAlertView 似乎根据设备宽度和高度结合 UIViewContentMode 计算图像显示区域的大小。这意味着在不同尺寸的设备上结果可能不同。由于 UIAlertView 的宽度为 540 像素,因此最好的解决方案是使用 540 像素 x 304 像素(16:9 比例)或更小的图像。这可确保警报大小在 iPhone 上与在 iPad 上相同。宽度大于 540 像素的图像以意想不到的方式呈现。

尽管试图将图像添加到 UIAlertView,但在所有的 hacks 中,这个方法实际上尊重 UIAlertView 的标题和消息区域,并允许 accessibilityLabel accessibilityHint 功能。它也不会抑制 UIAlertView 按钮。

以下适用于 iOS 8、9、10 和 11 beta 的设备和模拟器。 (UIAlertView 也适用于 iOS 7,除了不显示的图像。)

只需确保准确指向正确的图像名称,否则会出现空格。


代码

let alertView = UIAlertView(title: "Alert title", message: "Alert message.", delegate: nil, cancelButtonTitle: "OK")
let imageView = UIImageView()
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.image = UIImage(named: "Image")
imageView.isAccessibilityElement = true
imageView.accessibilityLabel = "Image label"
imageView.accessibilityHint = "Image hint."
alertView.setValue(imageView, forKey: "accessoryView")
alertView.show()

图片

UIAlertView 具有 540 像素 x 304 像素的图像。

enter image description here

关于ios - 如何在 Swift 的 UIAlertView 中调整附件 View 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34492087/

相关文章:

ios - 如何在 App 开发中使用函数式编程

ios - 将 UIAlertView 单击转发到另一个 Controller

iphone - 仅在 iOS8 中,当 App 锁定为纵向时,UIAlertView 会更改为横向

iphone - 外部 UITableView 委托(delegate)如何隐藏 UISearchBar 键盘?

带有外部蓝牙键盘的 iOS 8 自定义键盘

ios - 从呈现 View Controller 推送 View Controller

swift - 如何在 Tomcat 上部署 Kitura 生成的服务器端 Swift 构建

ios - 使用动态高度将 View 固定到底部

ios - UIAlertView 展开 Segue 处理程序

ios - Clocationmanager Didupdatelocation 委托(delegate)在没有互联网的情况下不会被调用