简体   繁体   中英

Add image on center of Alert ViewController with transparent background

How to display image in center of alert viewController with transparent background of alert viewController. I wrote following code.

let image = UIImage(named: "ic_no_data")
        let imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40)
        let alertMessage = UIAlertController(title: "image", message: "", preferredStyle: .Alert)

        let backView = alertMessage.view.subviews.last?.subviews.last
        backView?.layer.cornerRadius = 10.0
        backView?.backgroundColor = UIColor.lightGrayColor()

        alertMessage.view.addSubview(imageView)

        let action = UIAlertAction(title:"", style: .Cancel, handler: nil)
        action.setValue(image, forKey: "image")
        alertMessage .addAction(action)
        self.presentViewController(alertMessage, animated: true, completion: nil)

It looks like this.

在此处输入图片说明

Please help me to solve this problem and thanks to all.

you can store you reference of imageView an alertMessage, and in completion of the present viewController you have the exact size of the alert view, so you can adjust the image according to the current alert rect.

try this code is in swift3 :

 self.present(alertMessage, animated: true, completion: {
            var frame = self.alertMessage.view.frame
            frame.origin = CGPoint(x: 0, y: 0) // add your location
            self.imageView.frame = frame
        })

UIAlertController doesn't support such changes in view hierarchy you'd be better using a custom extensible component that mimics the behavior of UIAlertController. The problem with UIAlertController is that you don't know how Apple will change its view hierarchy in the next version of iOS. And each time they change something you'll have to add code for a specific version of iOS which is really bad from the maintainability point of view.

For example CustomIOSAlertView: https://github.com/wimagguc/ios-custom-alertview .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM