How to create UIAlertView with Image - ios

Hello everyone i have a question, if is possible to create UIAlertView with Image in Swift and how? If someone could help me because i don't find some example on network in swift practice all in objective c in iOS 6 not in iOS 7 or higher. Thanks.

After iOS8 UIAlertView is deprecated so Apple recommends you to use UIAlertController instead of UIAlertView. And to accomplish what you asked you can look here

Here is a workaround that I used successfully.
let myImage = UIImage(name:"myImage")
let prevImage = UIImageView(frame: CGRect(x: 10, y: 50, width: 250, height: 172))
prevImage.image = myImage
let spacer = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
let previewController = UIAlertController(title: "PREVIEW", message: spacer, preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "SAVE", style: .Default) { (UIAlertAction) in
self.uploadPatientPhoto(myImage!)
}
let retakeAction = UIAlertAction(title: "RETAKE", style: .Default) { (UIAlertAction) in
self.retakeNewPatientPhoto(self)
}
let cancelAction = UIAlertAction(title: "CANCEL", style: .Cancel, handler: nil)
previewController.addAction(saveAction)
previewController.addAction(retakeAction)
previewController.addAction(cancelAction)
previewController.view.addSubview(prevImage)
presentViewController(previewController, animated: true, completion: nil)

Related

Swift TimePicker Show Into UIAlerController with Cancel and Save Button Action

My Scenario, I am trying to show TimePicker (Only showing HH:MM and AM or PM) within UIAlertController with Cancel and Save Button action. I tried below code but Its not working.
let myDatePicker: UIDatePicker = UIDatePicker()
myDatePicker.timeZone = NSTimeZone.local
myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
alertController.view.addSubview(myDatePicker)
let selectAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: { _ in
print("Selected Date: \(myDatePicker.date)")
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alertController.addAction(selectAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion:{})
fixed this issue by using below line
myDatePicker.datePickerMode = .time

Custom UIAlertController with image

I have a UIAlertController implementation with two actions:
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)
Now, I want to add an image (at center) below the title, with the two actions still being aligned as in the picture. What I have tried to do is create a UIImageView and add it to alertcontroller as:
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)
But I cannot get it at the center of the alert. Is this the correct way? Or is there some other easy method to achieve this? How can I achieve this?
Use the following extension which allows to fully customise 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
}
}

Swift Add arrow and sourceView to UIAlertController

I have a UIAlertController and I am trying to add an arrow to it and change the sourceView to self.button so it does not appear at the bottom.
This is what I got so far:
let dropdown = UIAlertController(title: "Select Room", message: nil, preferredStyle: .ActionSheet)
let kitchen = UIAlertAction(title: "Kitchen", style: .Default) { (action) in
}
dropdown.addAction(kitchen)
let livingRoom = UIAlertAction(title: "Living Room", style: .Default) { (action) in
}
dropdown.addAction(livingRoom)
let bedroom = UIAlertAction(title: "Bedroom", style: .Default) { (action) in
}
dropdown.addAction(bedroom)
let bathroom = UIAlertAction(title: "Bathroom", style: .Default) { (action) in
}
dropdown.addAction(bathroom)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
}
dropdown.addAction(cancel)
dropdown.modalPresentationStyle = .Popover
dropdown.popoverPresentationController?.sourceRect = self.dropdownButton.frame
dropdown.popoverPresentationController?.sourceView = self.dropdownButton
dropdown.popoverPresentationController?.permittedArrowDirections = .Up
self.presentViewController(dropdown, animated: true, completion: nil)
But the arrow does not appear and the UIAlertController still appears at the bottom. What Am I doing wrong?
popoverPresentationController (and it's settings) are meant to be used by a UIViewController who's presentationStyle is UIModalPresentationPopover.
While UIAlertController is a subclass of UIViewController, it is special and uses UIModalPresentationCustom as it's presentationStyle. Attempts to set a new presentationStyle are ignored.
I don't think what you are trying to do is an intended use for UIAlertController. You best bet is to make your own view controller to achieve this purpose.

Custom Action controller, Swift

Does anyone know how I can code up this custom alert controller (The top area especially) - currently found on the Apple music App. Maybe there is a known library that can do it.
I am aware this is how you an action controller is coded?
let alertController = UIAlertController(title: nil, message: "Top Message Here", preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// Drop View Pop up
}
alertController.addAction(cancelAction)
let action1 = UIAlertAction(title: "Action Title", style: .Default) { (action) in
//Code to Execute
}
alertController.addAction(action1)
self.presentViewController(alertController, animated: true) {
// ...
}
Here is an example:
#IBAction func show() {
let actionSheet = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: .ActionSheet)
let view = UIView(frame: CGRect(x: 8.0, y: 8.0, width: actionSheet.view.bounds.size.width - 8.0 * 4.5, height: 120.0))
view.backgroundColor = UIColor.greenColor()
actionSheet.view.addSubview(view)
actionSheet.addAction(UIAlertAction(title: "Add to a Playlist", style: .Default, handler: nil))
actionSheet.addAction(UIAlertAction(title: "Create Playlist", style: .Default, handler: nil))
actionSheet.addAction(UIAlertAction(title: "Remove from this Playlist", style: .Default, handler: nil))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(actionSheet, animated: true, completion: nil)
}
If you're ok with deviating from the UIKit components, I have created a library for custom action sheets. It's written in Swift and lets you create custom sheets with several built-in item types. It can be extended and restyled as well.

Adding an image to a UIAlertController

This is my alert that works perfectly. I want to add an image to the alert that shows up along side the text when the alert is presented and I'm in an SKScene in SpriteKit if it makes a difference.
var alertController = UIAlertController(title: "How to Skate", message: "Tap the screen to perform a trick and jump over the obsticles (You can grind on rails) The game will end when you hit a highlighted red, orange or yellow obstacle. That's it! + Image", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Cool!", style: UIAlertActionStyle.Cancel, handler: nil))
self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
You can add a UIImageView as a subview to your UIAlertController.
var imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40))
imageView.image = yourImage
alert.view.addSubview(imageView)
This is how you do in UIAlertController:
let alertMessage = UIAlertController(title: "My Title", message: "My Message", preferredStyle: .Alert)
let image = UIImage(named: "myImage")
var action = UIAlertAction(title: "OK", style: .Default, handler: nil)
action.setValue(image, forKey: "image")
alertMessage .addAction(action)
self.presentViewController(alertMessage, animated: true, completion: nil)
let alertMessage = UIAlertController(title: "My Title", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
action.setValue(UIImage(named: "task1.png")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
alertMessage .addAction(action)
self.present(alertMessage, animated: true, completion: nil)
Swift 3
You can do like this.
let imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40))
// imageView.image = UIImage(named: "ic_no_data")
let alertMessage = UIAlertController(title: "My Title", message: "", preferredStyle: .Alert)
let image = UIImage(named: "Image")
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
action.setValue(image, forKey: "image")
alertMessage .addAction(action)
self.presentViewController(alertMessage, animated: true, completion: nil)
alertMessage.view.addSubview(imageView)
Adding an image to a UIAlertController
Please try below code Swift 4 +
Add alertView Controller
let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert)
let image = UIImage(named:"feet")!
alert.addImage(image: image)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
Add Extension UIAlertController
func addImage(image: UIImage) {
let maxSize = CGSize(width: 240, height: 244)
let imgSize = image.size
var ratio:CGFloat!
if (imgSize.width > imgSize.height){
ratio = maxSize.width / imgSize.width
}else {
ratio = maxSize.height / imgSize.height
}
let scaleSize = CGSize(width: imgSize.width*ratio, height: imgSize.height*ratio)
var resizedImage = image.imageWithSize(scaleSize)
if (imgSize.height > imgSize.width) {
let left = (maxSize.width - resizedImage.size.width) / 2
resizedImage = resizedImage.withAlignmentRectInsets(UIEdgeInsetsMake(0, -left, 0, 0))
}
let imgAction = UIAlertAction(title: "", style: .default, handler: nil)
imgAction.isEnabled = false
imgAction.setValue(resizedImage.withRenderingMode(.alwaysOriginal), forKey: "image")
self.addAction(imgAction)
}
Add image view extension
extension UIImage {
func imageWithSize(_ size:CGSize) -> UIImage {
var scaledImageRect = CGRect.zero
let aspectWidth:CGFloat = size.width / self.size.width
let aspectHeight:CGFloat = size.height / self.size.height
let aspectRatio:CGFloat = min(aspectWidth, aspectHeight)
scaledImageRect.size.width = self.size.width * aspectRatio
scaledImageRect.size.height = self.size.height * aspectRatio
scaledImageRect.origin.x = (size.width - scaledImageRect.size.width) / 2.0
scaledImageRect.origin.y = (size.height - scaledImageRect.size.height) / 2.0
UIGraphicsBeginImageContextWithOptions(size, false, 0)
self.draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
If you're willing to use private APIs you could use the private attributedMessage property to set an attributed string as message containing an image:
Source: https://github.com/JaviSoto/iOS10-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UIAlertController.h
let actionSheet = UIAlertController(title: "title", message: nil, preferredStyle: .actionSheet)
let str = NSMutableAttributedString(string: "Message\n\n", attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1), NSAttributedStringKey.foregroundColor: UIColor.gray])
let attachment = NSTextAttachment()
attachment.image = --> yourImage <--
str.append(NSAttributedString(attachment: attachment))
actionSheet.setValue(str, forKey: "_attributedMessage")
Again, this is a private API and therefore could change in any release without notice. To be used with caution!
SWIFT 4 +
let refreshAlert = UIAlertController(title: "Unlike Article", message: "Are you sure you want to unlike this Article?", preferredStyle: UIAlertControllerStyle.alert)
let cancel = UIAlertAction(title: "CANCEL", style: .default, handler: { (action: UIAlertAction!) in
return
})
let image = #imageLiteral(resourceName: "dislike_icon").resizedImage(newSize: CGSize(width: 25, height: 25))
let unLike = UIAlertAction(title: "UNLIKE", style: .destructive, handler: { (action: UIAlertAction!) in
self.articleUnLiking()
return
})
unLike.setValue(image.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
refreshAlert.addAction(cancel)
refreshAlert.addAction(unLike)
self.present(refreshAlert, animated: true, completion: nil)
NOTE :- Again, this is a private API and therefore could change in any release without notice. To be used with caution!
THANKS
Currently there isn't really a proper way of doing that with UIAlertController without using private api or other hacks because according to documentation you should not modify view hierarchy of alert view controller. So the best solution would be to create a custom view for that. However if you do not care about some additional borders then using attributed string in UITextField works:
alertController.addTextField { field in
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(x: 0, y: 0, width: 226, height: 226)
field.attributedPlaceholder = NSAttributedString(attachment: attachment)
field.textAlignment = .center
field.isEnabled = false
}

Resources