can anyone please tell me a way of adding in an image into a UIAlertController? This is the code I have generated to produce the Alert Controller.
I believe I need to add a subview but not sure?
let myAlert = UIAlertController(title: "Congratualtions", message: "Correct answer selected, move on to next level", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default)
{
action in self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion:nil)
The code works but i do not know how add an image into the action sheet...
You can use this library (MZFormSheetPresentationController) to create the AlertViews with Images,Buttons and lots of functions. You can design viewController as you want...
func formSheetControllerWithNavigationController() -> UINavigationController {
return self.storyboard!.instantiateViewController(withIdentifier: "formSheetController") as! UINavigationController
}
func passDataToViewControllerAction() {
let navigationController = self.formSheetControllerWithNavigationController()
let formSheetController = MZFormSheetPresentationViewController(contentViewController: navigationController)
formSheetController.presentationController?.isTransparentTouchEnabled = false
formSheetController.presentationController?.shouldCenterVertically = true
formSheetController.presentationController?.shouldCenterHorizontally = true
formSheetController.presentationController?.shouldDismissOnBackgroundViewTap = true
let yourViewController = navigationController.viewControllers.first as! EventDisplayViewController
yourViewController.delegate = self
self.present(formSheetController, animated: true, completion: nil)
}
Related
// In UITableViewCell
// when I tab on screen it says "open image
2017-11-22 13:15:31.023129+0530 chat[1376:265960] Warning: Attempt to present on whose view is not in the window hierarchy!"
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("open image")
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc : openimageinfullscreen = sb.instantiateViewController(withIdentifier: "openimageinfullscreen") as! openimageinfullscreen
self.window?.rootViewController?.present(vc, animated: true, completion: nil)
}
You need to get the top presented view controller and then present.
Try this.
func topViewController() -> UIViewController? {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
}
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("open image")
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc : openimageinfullscreen = sb.instantiateViewController(withIdentifier: "openimageinfullscreen") as! openimageinfullscreen
self.topViewController()?.present(vc, animated: true, completion: nil)
}
On a separate note, You shouldn't use class name starts with small letter. openimageinfullscreen class should be OpenImageInFullscreen
What I am trying to do here is once login is successful, go to the "HomeLoginViewController" which is a navigation controller with its root controller being "HomepageViewController" but I also need to send the surname of the user that logged in to a label in the "HomepageViewController".
If I put the "self.presentViewController(controller, animated: true, completion: nil)" first then this goes to the "HomepageViewController" and sends the surname but does not display the navigation bar.
If I put the "self.presentViewController(alert, animated: true, completion: nil)" first it displays the navigation bar but does not send the surname. I cannot fix this code to do both :( Please help.
class LoginViewController: UIViewController {
let ref = Firebase(url: "https://<myfirebase>.firebaseio.com/")
#IBOutlet weak var forenamefield: UITextField!
#IBOutlet weak var surnamefield: UITextField!
#IBOutlet weak var emailfield: UITextField!
#IBOutlet weak var passwordfield: UITextField!
#IBOutlet weak var loginbutton: UIButton!
#IBAction func signinaction(sender: AnyObject) {
let user = self.forenamefield.text!
let usersurname = self.surnamefield.text!
ref.authUser(emailfield.text, password: passwordfield.text, withCompletionBlock: { error, authData in
if error != nil
{
let alert = UIAlertController(title: "Error", message: "Incorrect Email and Room Number.", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
print("Can Not Sign In")
}
else
{
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewName:NSString = "HomeView"
let vc = storyboard.instantiateViewControllerWithIdentifier(viewName as String) as! HomeLoginViewController
let controller = storyboard.instantiateViewControllerWithIdentifier("ViewHome") as! HomepageViewController
controller.labelText = self.surnamefield.text!
let uid = authData.uid
print("Success with user: \(uid)")
let alert = UIAlertController(title: "Success", message: "Welcome \(user) \(usersurname)", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: .Default) { _ in
self.navigationController?.presentViewController(vc, animated: true, completion: nil)
}
alert.addAction(action)
self.presentViewController(controller, animated: true, completion: nil)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
You can try use NSUserDefaults when login details are correct
// In login screen before go to home, save the username as key "userID"
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(username, forKey: "userID")
defaults.synchronize()
// In your home, viewDidLoad() retrieve it back
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let userID = (defaults.objectForKey("userID") as? String)!
So, some of my users don't realize they can hold a cell to get an alert pop-up with options. So, I would like to add some kind of image or text or color - something - to let the user know "hey, you can hold this to get more info." Here is my code below. Any thoughts on the best way to do this?
// handles long press for editing or sharing a search
func tableViewCellLongPressed(
sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began &&
!tableView.editing {
let cell = sender.view as! UITableViewCell // get cell
if let indexPath = tableView.indexPathForCell(cell) {
displayLongPressOptions(indexPath.row)
}
}
}
// displays the edit/share options
func displayLongPressOptions(row: Int) {
// create UIAlertController for user input
let alertController = UIAlertController(title: "Helpful Stuff",
message: "",
preferredStyle: UIAlertControllerStyle.Alert)
// create Cancel action
let cancelAction = UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
let shareAction = UIAlertAction(title: "Share",
style: UIAlertActionStyle.Default,
handler: {(action) in self.shareSearch(row)})
alertController.addAction(shareAction)
presentViewController(alertController, animated: true,
completion: nil)
}
// callback that returns a configured cell for the given NSIndexPath
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
// get cell
let cell = tableView.dequeueReusableCellWithIdentifier(
"Cell", forIndexPath: indexPath) as UITableViewCell
// set cell label's text to the tag at the specified index
cell.textLabel?.text = model.tagAtIndex(indexPath.row)
// set up long press guesture recognizer
let longPressGestureRecognizer = UILongPressGestureRecognizer(
target: self, action: "tableViewCellLongPressed:")
longPressGestureRecognizer.minimumPressDuration = 0.5
cell.addGestureRecognizer(longPressGestureRecognizer)
return cell
}
If you want to use the Storyboard, that may be easier to hook up the gesture recognizer and link that to the button in the Storyboard, instead of having it in the cellForRowAtIndexPath, which is called many times
I have a tableView, and when the user taps a cell, it opens an alert box with the options "Close" and "Search". The handler for "Search" is shown below as func searchSongAction.
This presents a new viewcontroller (embedded in a Nav Bar) that searches the song online. In this new viewcontroller, Search, there are 2 functions: one searches the song currently playing and the other searches the song that the user asked to search from the tableView alert.
I am trying to pass the data from the cell into the Search class, but I keep coming up short. I feel like what I have is correct, but that is obviously not he case.
Any ideas?
Ask me if you need any more information.
History.swift
func searchSongAction(alert: UIAlertAction!) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("Search") as! Search
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationNavigationController = segue.destinationViewController as! UINavigationController
let targetController = destinationNavigationController.topViewController as! Search
targetController.searchType = "Previous"
targetController.songNowText = self.songToSearch
targetController.artistNowText = self.artistToSearch
}
Search.swift
class Search: UIViewController {
var songNowText = ""
var artistNowText = ""
var searchType = ""
override func viewDidLoad() {
super.viewDidLoad()
if searchType == "Previous" {
searchSongPrevious()
} else {
searchSongNow()
}
}
}
You're not actually performing a Segue from your searchSongAction: function, so I'm guessing that prepareForSegue:sender: isn't actually being called and therefore the setup is not running.
Try assigning searchType, songNowText and artistNowText on vc inside of searchSongAction::
func searchSongAction(alert: UIAlertAction!) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("Search") as! Search
//Setup the properties
vc.searchType = "Previous"
vc.songNowText = self.songToSearch
vc.artistNowText = self.artistToSearch
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
As a side note, typically you'll want to call super's implementation of a function when overriding it (you have neglected to do this in prepareForSegue:sender:)
I'm trying to create a profilePic in a Sign Up View Controller. The profilePic is of type UIImageView. I want to be able to tap it so it instantly pulls up a photo library in an ActionSheet Style. And to also have one of the image box a button to access the camera. Is this possible?
import UIKit
class SignUpViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// PROFILE PICTURE
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
}
}
Try this code below :
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate {
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
showActionSheet()
}
}
func camera()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
profilePic.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Its working on my side..hope will do the some for you !
I recently published a GitHub repository to handle this type of Action Sheet.
You can download this class from here : MSActionSheet
and simply write :
EDIT :
● Now supporting iPad
MSActionSheet(viewController: self, sourceView: sender).showFullActionSheet {
sender.setImage($0, for: .normal)
}
MSActionSheet : is the best library for set user's profile picture.
I used this library but it's not supported in iPad so i
customise for some functions for support to iPad and Display with
popOverController.
Below the step of customisation.
Replace function with showFullActionSheet
func showFullActionSheet(on vc : UIViewController, over btn : UIButton,handler : #escaping (_ : UIImage?) -> Void) {
let sheet = create().addLibrary().addFrontCamera().addRearCamera().addCancelButton()
sheet.show(on: vc,over: btn){ (image : UIImage?) in
handler(image)
}
}
Add code before vc.present(MSActionSheet.sheet!, animated: true, completion: nil) in function show
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
if let presenter = MSActionSheet.sheet?.popoverPresentationController {
presenter.sourceView = btn
presenter.sourceRect = btn.bounds
}
}
Add below code before clientVC?.present(picker, animated: true, completion: nil) in function handler
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
picker.modalPresentationStyle = .popover
if let presenter = picker.popoverPresentationController {
presenter.sourceView = sourceBtn
presenter.sourceRect = sourceBtn!.bounds
}
}
How to use
let msActionSheet = MSActionSheet.instance
msActionSheet.showFullActionSheet(on: self,over: btn){ (image) in
btn.setImage(image, for: .normal)
}
msActionSheet.tintColor(color: Constants.kColorBluish)
Swift 3x:
class yourClassName:UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBAction func yourButtonName(_ sender: UIButton) {
let pickerView = UIImagePickerController()
pickerView.delegate = self
pickerView.allowsEditing = true
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: nil, preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel") //Cancel
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton: UIAlertAction = UIAlertAction(title: "Take Photo", style: .default) { action -> Void in
print("Take Photo") //Will open Camera
if UIImagePickerController.isSourceTypeAvailable(.camera) {
pickerView.sourceType = .camera
self.present(pickerView, animated: true, completion: { _ in })
}
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton: UIAlertAction = UIAlertAction(title: "Camera Roll", style: .default) { action -> Void in
print("Camera Roll") //Will open Gallery
pickerView.sourceType = .photoLibrary
self.present(pickerView, animated: true, completion: { _ in })
}
actionSheetControllerIOS8.addAction(deleteActionButton)
let deleteActionButton2: UIAlertAction = UIAlertAction(title: "Import from Facebook", style: .default) { action -> Void in
print("Import from Facebook")
}
actionSheetControllerIOS8.addAction(deleteActionButton2)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//print(info)
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
//print(pickedImage)
yourImageView.contentMode = .scaleAspectFit
yourImageView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
}