具有图像

时间:2017-12-26 14:54:45

标签: ios swift uiimageview uialertcontroller

我有一个带有两个动作的UIAlertController实现:

let alert = UIAlertController(title: "Add your photo", message: "", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Add Later", style: .cancel) { (action) -> Void in }
let uploadAction =  UIAlertAction(title: "Upload", style: .default) { (action) -> Void in }
alert.addAction(cancelAction)
alert.addAction(uploadAction)
present(alert, animated: true, completion: nil)

enter image description here

现在,我想在标题下方添加一个图像(位于中央),两个动作仍然如图所示对齐。我试图做的是创建一个UIImageView并将其添加到alertcontroller:

let image = UIImage(named: "myimage.png")
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: alert.view.frame.width/2, y: alert.view.frame.height/2, width: 50, height: 50)
alert.view.addSubview(imageView)

但我不能把它放在警报的中心。这是正确的方法吗?或者还有其他一些简单的方法来实现这一目标吗?我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:-2)

使用以下扩展名允许完全自定义UIAlertController: -

extension UIAlertAction{
    @NSManaged var image: UIImage?

    convenience init(title: String?, style: UIAlertActionStyle,image : UIImage?, handler: ((UIAlertAction) -> Swift.Void)? = nil ){
        self.init(title: title, style: style, handler: handler)
        self.image = image
    }
}