Łukasz Betta
Łukasz Betta

Reputation: 161

Swift - UIAlertController with image

I have this code:

let alert = UIAlertController(title:"title", preferredStyle: UIAlertControllerStyle.alert)
    let saveAction = UIAlertAction(title: "Title", style: .default, handler: nil)

    var imageView = UIImageView(frame: CGRectMake(10, 10, 250, 124))
    imageView.image = zdjecieGlowne
    alert.view.addSubview(imageView)

    alert.addAction(UIAlertAction(title: "Button 1", style: UIAlertActionStyle.default, handler: { alertAction in
        print("1 pressed")
    }))
    alert.addAction(UIAlertAction(title: "Button 2", style: UIAlertActionStyle.cancel, handler: { alertAction in
        print("2 pressed")
    }))
    alert.addAction(UIAlertAction(title: "Button 3", style: UIAlertActionStyle.default, handler: { alertAction in
        print("3 pressed")
    }))
    self.present(alert, animated: true, completion: nil)
}

The window looks like this: https://ibb.co/hM5zHH

The picture covers me with the buttons. Does anyone know how to fix it?

Upvotes: 2

Views: 8205

Answers (3)

Lengyel Viktor
Lengyel Viktor

Reputation: 31

Here is my solution. (the empty lines increase the size to another subview)

let alert = UIAlertController(title: msg.title, message: 

"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",preferredStyle .alert)
            
var imageView = UIImageView(frame: CGRect(x: 10, y: 50, width: 250, height: 124))
imageView.image = try? UIImage(data: Data(contentsOf: URL(string: msg.picture)!))
            
let textView = UITextView(frame: CGRect(x: 10, y: 180, width: 250.0, height: 330))
textView.text = msg.text
textView.backgroundColor = (UIColor) .clear
            
alert.view.addSubview(imageView)
alert.view.addSubview(textView)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler:{ _ in _ = self.navigationController?.popViewController(animated: true)
}))
            
alert.view.tintColor = UIColor.dustyOrange
self.present(alert, animated: true)

Upvotes: 3

Rohit Makwana
Rohit Makwana

Reputation: 4905

Try this, it may helps you

    let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)

    //Add imageview to alert
    let imgViewTitle = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
    imgViewTitle.image = UIImage(named:"image.png")
    alert.view.addSubview(imgViewTitle)

    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)

Upvotes: 7

mkowal87
mkowal87

Reputation: 626

In my opinion UIAlertController shouldn't be used to show some option with image, instead you should implement custom UIView and handle presentation logic.

Upvotes: 3

Related Questions