将图片添加到警告视图

25

当用户按下添加按钮时,我有一个弹出式警报视图。如何向警报视图添加图像?

我添加了一些代码,参考自Stack Overflow。我的保存按钮被替换为图像,图像看起来是蓝色的...

警报视图的代码

var alert = UIAlertController(title: "Spring Element \(springNumber)",
            message: "Add spring properties",
            preferredStyle: .Alert)

        let saveAction = UIAlertAction(title: "Save",
            style: .Default) { (action: UIAlertAction!) -> Void in

                let textField1 = alert.textFields![0] as UITextField
                self.txtField1.append(textField1.text)
                self.tableView.reloadData()

                let textField2 = alert.textFields![1] as UITextField
                self.txtField2.append(textField2.text)
                self.tableView.reloadData()

                println(self.txtField1)
                println(self.txtField2)
        }

        let cancelAction = UIAlertAction(title: "Cancel",
            style: .Default) { (action: UIAlertAction!) -> Void in
        }

        //adding textfield1
        alert.addTextFieldWithConfigurationHandler {
            (textField1: UITextField!) -> Void in
            textField1.placeholder = "Force"
        }

        //adding textfield2
        alert.addTextFieldWithConfigurationHandler {
            (textField2: UITextField!) -> Void in
            textField2.placeholder = "Stiffness"
        }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)

图片浏览代码

   let image = UIImage(named: "springAtWall")
    saveAction.setValue(image, forKey: "image")
    alert.addAction(saveAction)
6个回答

34

是的,你可以将UIImageView作为子视图添加到你的警告视图中。

var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = yourImage

alert.view.addSubview(imageView)

1
谢谢您提供的解决方案。不过这个有点太小了。是否有任何建议可以使图像变大,并出现在消息下方但在文本字段上方? - Cherry_thia
你如何将图像作为背景图像,放在文字后面? - μολὼν.λαβέ
1
这种方法被苹果明确禁止。此外,CGRectMake() 方法不起作用,因为您需要传递一个负的 y 值来将图像定位到中心位置。 - slider
表面上看起来还好,但这不是一个好的方法。当用户在辅助功能设置中更改文本大小时,它会出现问题。警告视图文本会与图像重叠并可能被覆盖。 - user4806509
1
@chicobermuda 我知道现在已经过去了很长时间,但是为了记录,禁止调整警报控制器的文档可以在这里找到:https://developer.apple.com/documentation/uikit/uialertcontroller。请注意“重要”框中的内容,其中写道`UIAlertController类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不得修改。` - Ash
显示剩余7条评论

27

这里是 Swift 4 的解决方案:

let showAlert = UIAlertController(title: "Demo Alert", message: nil, preferredStyle: .alert)
let imageView = UIImageView(frame: CGRect(x: 10, y: 50, width: 250, height: 230))
imageView.image = image // Your image here...
showAlert.view.addSubview(imageView)
let height = NSLayoutConstraint(item: showAlert.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 320)
let width = NSLayoutConstraint(item: showAlert.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 250)
showAlert.view.addConstraint(height)
showAlert.view.addConstraint(width)
showAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
    // your actions here...    
}))
self.present(showAlert, animated: true, completion: nil)

对于所有的iPhone,输出将类似于以下内容:

带图像的警报


1
那是我的错误,不是“showQRCodeAlert”,而是“showAlert”。我们需要通过警报的根视图来配置警报中的任何视图。所以我已经编辑了那个答案,你可以检查一下。 - Hardik Trivedi
1
很棒的解决方案,正是我所需要的。 - Jonas

7

Swift 4:

var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = <#yourImage#>
alert.view.addSubview(imageView)

5
我们可以像这样在警报视图控制器中添加图像作为一个选项。
   let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 196, height: 196)))
    imageView.image = image

    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, imageView.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    let context = UIGraphicsGetCurrentContext()
    imageView.layer.render(in: context!)
    let finalImage = UIGraphicsGetImageFromCurrentImageContext()

    let alertMessage = UIAlertController(title: "Your Title", message: "", preferredStyle: .alert)
    let action = UIAlertAction(title: "", style: .default, handler: nil)
    action.setValue(finalImage?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
    alertMessage .addAction(action)
    let action1 = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertMessage .addAction(action1)

    self.present(alertMessage, animated: true, completion: nil)

0
func launchAlertTool(image: UIImage, topViewController: UIViewController) {
        let alert = UIAlertController(title: "Add Comments",
                                      message: nil,
                                      preferredStyle: .alert)
        
        let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
        subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)
        let imageView = UIImageView(frame: CGRect(x: 0, y: 100, width: topViewController.view.bounds.width, height: topViewController.view.bounds.width - 150))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        alert.view.addSubview(imageView)
        alert.view.tintColor = .black
        
        let height = NSLayoutConstraint(item: alert.view as Any, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: topViewController.view.bounds.width)
        let width = NSLayoutConstraint(item: alert.view as Any, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: topViewController.view.bounds.width)
        alert.view.addConstraint(height)
        alert.view.addConstraint(width)
        
        alert.addTextField { (textField) in
            // optionally configure the text field
            textField.keyboardType = .alphabet
            textField.textAlignment = .center
            textField.tintColor = .systemPink
        }
        
        let okAction = UIAlertAction(title: "Share", style: .default) { [unowned alert] (action) in
            if let textField = alert.textFields?.first {
                let comment = textField.text ?? "Check this image"
                let shareAll = [comment, screenShot] as [Any]
                let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
                activityViewController.popoverPresentationController?.sourceView = topViewController.view
                topViewController.navigationController?.present(activityViewController, animated: true, completion: {
                })
            }
        }
        alert.addAction(okAction)
        if let topVC = UIApplication.getTopViewController() {
            topVC.present(alert, animated: true, completion: {
            })
        }
    }

0

一开始我并不清楚@Kakumanu的ImageContext是用来做什么的,但它可以调整UIImage的大小。也许更Swifty的方法是通过UIImage扩展实现```

extension UIImage {
/// Resize a UIImage
func imageWith(newSize: CGSize) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: newSize)
    let image = renderer.image { _ in
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
    }
    return image.withRenderingMode(self.renderingMode)
 }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接