I want to share an image using UIActivityViewController. I am able to display the text I want to share, but I can't really figure out how to add an image. Hope somebody could help me. Thanks!
My code is displayed under "actionButton"
import UIKit
class DetailViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var myDetailedImageView: UIImageView!
var myDetailedImageName: String?
var nameString: String?
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
//For setting max and min zoom
scrollView.maximumZoomScale = 0.8
scrollView.minimumZoomScale = 0.15
scrollView.delegate = self
//reset zoomzcale for new image
self.scrollView.zoomScale = 0.15
self.myDetailedImageView.image = UIImage(named: myDetailedImageName!)
}
#IBAction func actionButton(sender: AnyObject) {
let firstActivityItem = NSString(string: myDetailedImageName!)
let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
//Showing what to zoom/scroll
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
//returning image to reload it self
return myDetailedImageView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Just like with a text:
let activityViewController = UIActivityViewController(activityItems: [firstActivityItem, self.myDetailedImageView.image!], applicationActivities: nil)
Related
The image is not from one VC to another VC.
The problem is displaying it to the image view in the main UIViewController. I have everything hooked up correctly in the Storyboard.
Click here to view my storyboard layout.
Please note some of my unnecessary code has been removed from both ViewController classes.
Here is my first UIViewController:
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var imagePicker: UIImagePickerController!
#IBAction func editPhoto(_ sender: UIButton) {
let ViewController2 = storyboard?.instantiateViewController(withIdentifier: "AddNewEaterySegue") as! ViewController2
ViewController2.imageForEdit = imageView.image!
print(imageView)
print(imageView.image!)
navigationController?.pushViewController(ViewController2, animated: true)
}
#IBOutlet weak var imageView: UIImageView! {
didSet {
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
}
}
Here is my second UIViewController:
import UIKit
class ViewController2: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var filter : CIFilter!
var imageForEdit = UIImage()
var imagePicker: UIImagePickerController!
#IBOutlet weak var select: UISegmentedControl!
#IBOutlet weak var imageLabel: UIImageView!
#IBOutlet weak var textField: UITextField!
#IBAction func saveButtonPressed(_ sender: UIImage) {
if textField.text == "" {
print("Не все поля заполнены")
} else {
}
performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
}
override func viewDidLoad() {
super.viewDidLoad()
imageLabel.image = imageForEdit
print(imageLabel)
// Do any additional setup after loading the view.
}
#IBAction func tappedEnter(_ sender: Any) {
if textField.text?.isEmpty ?? true {
return
} else {
if let texttxt = textField.text {
let data = texttxt.data(using: .ascii, allowLossyConversion: false)
if select.selectedSegmentIndex == 0
{
filter = CIFilter(name: "CICode128BarcodeGenerator")
} else {
filter = CIFilter(name: "CIQRCodeGenerator")
}
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 5, y: 5)
let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
imageLabel.image = image
}
}
}
}
When you are pushing to ViewController2 your imageView in ViewController is empty.
Where exactly are you setting the image for imageView?
In your storyboard, the imageView in ViewController is empty and also in the didSet method for imageView in ViewController you have not set any image to the imageView.
Try this in ViewController:
#IBOutlet weak var imageView: UIImageView! {
didSet {
//Add a test image to your project.
imageView.image = UIImage(named: "YOUR_TEST_IMAGE_NAME.jpeg")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
}
EDIT: Ok I guess I was not clear on your question. So in order to send the image from "ViewController2" back to "ViewController", you can use many methods but the way I would do it is by using Protocols.
I have done it in a generic way but you can apply this to send any kind of data from one view controller back to the previous view controller.
Try this in ViewController:
import UIKit
protocol ImageViewProtocol{
func sendImageToViewController(theImage: UIImage)
}
class ViewController: UIViewController, ImageViewProtocol {
func sendImageToViewController(theImage: UIImage) {
imageView.image = theImage
}
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewcontroller2") as! ViewController2
viewcontroller2.delegate = self
self.navigationController?.pushViewController(viewcontroller2, animated: true)
}
}
Try this in ViewController2:
import UIKit
class ViewController2: UIViewController {
var delegate: ImageViewProtocol!
#IBOutlet weak var barcodeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
barcodeImageView.image = UIImage(named: "test_image.jpg")
}
#IBAction func saveButtonAction(_ sender: Any) {
delegate.sendImageToViewController(theImage: barcodeImageView.image!)
self.navigationController?.popViewController(animated: true)
}
}
I'm working with Swift 2 in xCode 7. Building a single view app. What I'm trying to do is allow the user to access their photo library, select an image, and then record some audio.
I setup an UIImageView view for where the selected photo will go and then a UIToolbar with three UIBarButtonItems: Image , Record, Play. Clicking on 'Image' will bring up the user's photo library to pick a photo from.
Here is my code:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var imageView: UIImageView!
#IBOutlet var imgSlctBtn: UIBarButtonItem!
#IBOutlet var recordBtn: UIBarButtonItem!
#IBOutlet var playBtn: UIBarButtonItem!
#IBOutlet var toolbar: UIToolbar!
var soundRecorder : AVAudioRecorder!
var soundPlayer : AVAudioPlayer!
var fileName = "micFlagRecording"
var imagePicker = UIImagePickerController()
var newFileName = ""
let userDefaults = NSUserDefaults.standardUserDefaults()
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.contentMode = .ScaleAspectFit
imageView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
func getCacheDirectory() -> String {
. . .
}
func saveFileReference() {
. . .
}
func newFileURL() -> NSURL {
. . .
}
func getFileURL() -> NSURL {
. . .
}
func setupRecorder() {
. . .
}
func preparePlayer() {
. . .
}
#IBAction func record(sender: UIBarButtonItem) {
print("record started")
if sender.title == "Record" {
soundRecorder.record()
recordBtn.title = "Stop"
} else {
soundRecorder.stop()
recordBtn.title = "Record"
playBtn.enabled = true
}
}
#IBAction func play(sender: UIBarButtonItem) {
if sender.title == "Play" {
recordBtn.enabled = false
sender.title = "Stop"
preparePlayer()
soundPlayer.play()
} else {
soundPlayer.stop()
sender.title = "Play"
recordBtn.enabled = true
}
}
#IBAction func initImgSlct(sender: UIBarButtonItem) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
playBtn.enabled = false
imagePicker.delegate = self
setupRecorder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
What happens when I try out this code is recording and play back work just fine. However, after I select an image from the photo library by clicking "Image" (which calls the IBAction func initImgSlct) the UIBarButtonItems are still clicking but none of the IBActions are triggered.
I was thinking the issue has to do with my dismissViewController on ImagePickerController is not returning delegation back to my ViewController? I'm new to Swift so that could be way off.
Thanks for your patience and help!
I'm having trouble getting the following code to compile, any suggestions people?
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var avatar: UIImageView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var contentImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
avatar.layer.cornerRadius = 5.0
avatar.layer.borderWidth = 4.0
avatar.layer.borderColor = UIColor.whiteColor().CGColor
avatar.clipsToBounds = true
scrollView.delegate = self
contentImageView.clipsToBounds = true
}
override func viewDidAppear(animated: Bool) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("LoginScreen") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let yOffset = self.scrollView.contentOffset.y * 0.2
let availableOffset = min(yOffset, 60)
let contentRectYOffset = availableOffset / contentImageView.frame.size.height
contentImageView.layer.contentsRect = CGRectMake(0.0, contentRectYOffset, 1, 1);
}
}
The error is
'Downcast from 'UIViewController?' to 'UIViewController' only unwraps
optionals; did you mean to use '!'
This happens in the line
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("LoginScreen") as! UIViewController
You are force down casting an object which is already of same type. You just need to remove as! UIViewController and assuming the ViewController with identifier LoginScreen exists, you can force unwrap the vc variable when needed.
override func viewDidAppear(animated: Bool) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("LoginScreen")
self.presentViewController(vc!, animated: true, completion: nil)
}
Thanks R P, your solution worked a treat.
override func viewDidAppear(animated: Bool) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("LoginScreen")
self.presentViewController(vc!, animated: true, completion: nil)
}
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
let imagePicker = UIImagePickerController()
#IBOutlet var ImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imagePicker.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
#IBAction func Select(sender: AnyObject) {
//imagePicker.sourceType =
// UIImagePickerControllerSourceType.PhotoLibrary
//imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
ImageView.contentMode = .ScaleAspectFit
ImageView.image = image
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
I stumped on why the UIImage picked by the PickerController is not set to UIImageView. Can any one please provide insight into what I am missing here?
You have #IBOutlet var ImageView: UIImageView! in your code, but you are getting the error "UIView setImage:]: unrecognized selector". This means that you configured your view in Interface Builder as a UIView, rather than a UIImageView. You need to set up a UIImageView to be able to set the image.
Just for future reference the other reason this might happen is because you've accidentally connected the wrong UI element to your UIImageView property.
For example I dragged a NSConstraint to the UIImageView, and got the same error.
In my current project i have detail view that shows a specific record from my table view. I have the following labels
#IBOutlet weak var vacationImageView: UIImageView!
#IBOutlet weak var percentSaved: UILabel!
#IBOutlet weak var cost: UILabel!
#IBOutlet weak var saved: UILabel!
#IBOutlet weak var circleProgressView: CircularProgressView!
#IBOutlet weak var daysDepart: UILabel!
I call a popover that I want to send the current text value of saved to my popup, allow the user to edit it and send it back to the view. Here is my popover call.
#IBAction func addPopover(sender: UIView) {
let savingsInformationViewController = storyboard?.instantiateViewControllerWithIdentifier("SavingsAddPopover") as UIViewController
savingsInformationViewController.modalPresentationStyle = .Popover
savingsInformationViewController.preferredContentSize = CGSizeMake(200, 200)
let popoverController = savingsInformationViewController.popoverPresentationController
popoverController?.sourceView = sender
popoverController?.permittedArrowDirections = .Any
popoverController?.delegate = self
presentViewController(savingsInformationViewController, animated: true, completion: nil)
}
I would have thought I could reference the data object from the popover but can't..at least not the way I'm thinking.
class ViewController: UIViewController,SavingViewControllerDelegate,UIPopoverPresentationControllerDelegate{
#IBOutlet var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func buttonPopOverClick(sender: UIButton)
{
let savingsInformationViewController = storyboard?.instantiateViewControllerWithIdentifier("SavingsAddPopoverVC") as SavingViewController
savingsInformationViewController.delegate = self
savingsInformationViewController.strSaveText=labelText.text
savingsInformationViewController.modalPresentationStyle = .Popover
if let popoverController = savingsInformationViewController.popoverPresentationController {
popoverController.sourceView = sender
popoverController.sourceRect = sender.bounds
popoverController.permittedArrowDirections = .Any
popoverController.delegate = self
}
presentViewController(savingsInformationViewController, animated: true, completion: nil)
}
func saveText(strText: NSString) {
labelText.text=strText
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
return .FullScreen
}
func presentationController(controller: UIPresentationController!, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController! {
return UINavigationController(rootViewController: controller.presentedViewController)
}
}
protocol SavingViewControllerDelegate
{
func saveText(var strText : NSString)
}
class SavingViewController: UIViewController {
#IBOutlet var textField: UITextField!
var delegate : SavingViewControllerDelegate?
var strSaveText : NSString!
override func viewDidLoad() {
super.viewDidLoad()
textField.text = strSaveText
// Do any additional setup after loading the view.
}
#IBAction func buttonDone(sender: UIButton)
{
if (self.delegate) != nil
{
delegate?.saveText(textField.text)
self.dismissViewControllerAnimated(true, nil)
}
}
}
just to point out
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
return .none
}
not woking properly on ios 12 /xcode 11, at least for popover tableview controller
The call below works
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}