Update a collection view in an other view - swift

For school I have to make an iOS application. I would like to use an UICollectionView in an other View. I use the following code, but when I use self.libraryCollectionView.reloadData(), the collectionView function is not called. The CollectionView with the name libraryCollectionView should hold an gallery of Images.
Here you can see the code I wrote.
import UIKit
class CoverViewController: UIViewController, UICollectionViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDataSource {
// MARK: Properties
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var typeLabel: UILabel!
#IBOutlet weak var libraryCollectionView: UICollectionView!
var cover: Cover?
var images = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
// Set up views if editing an existing Cover.
if let cover = cover {
photoImageView.image = cover.image
typeLabel.text = cover.type
}
libraryCollectionView.delegate = self
libraryCollectionView.dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
#IBAction func addImage(_ sender: UIBarButtonItem) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet);
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.sourceType = .camera
self.present(imagePicker, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action) in
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
imagePicker.sourceType = .photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
// Methods for ImagePicker
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
images.append(pickedImage)
DispatchQueue.main.async{
self.libraryCollectionView.reloadData()
}
}
dismiss(animated: true, completion: nil)
}
// Methods for CollectionView
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellIdentifier = "cell"
let cell = libraryCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ImageCellView
NSLog(String(images.count))
cell.photoImageView.image = images[indexPath.row]
return cell
}
}

numberOfSections(in collectionView: UICollectionView) should return at least 1.
It's default value is also 1, so you can just delete the whole method from your code.

Related

PerformSegue from long press on a a custom UiTableViewCell

maybe the question has been asked several times, but can't find it.
I'm a newbie.
I have a UITableView with a custom UITableViewCell.
in the cell there are 3 different labels.
I added the gesture recognizer on the custom cell, so that if long press is done on a label :
- label 1 should show another UiViewController
- label 2 should do a call
- label 3 should create a mail
for labels 2 and 3 i had no problem
but how to perform the segue to open the view controller ?
This is the storyboard
This is the custom tableviewcell
import UIKit
import MessageUI
class OfficeCell: UITableViewCell, MFMailComposeViewControllerDelegate {
#IBOutlet weak var lbOffice: UILabel!
#IBOutlet weak var lbAddress: UILabel!
#IBOutlet weak var lbPhone: UILabel!
#IBOutlet weak var lbMail: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.setupLabelTap()
// Configure the view for the selected state
}
func setupLabelTap() {
let lbAddressTap = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressReconizer(_:)))
self.lbAddress.isUserInteractionEnabled = true
self.lbAddress.addGestureRecognizer(lbAddressTap)
let lbAddressTap2 = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressReconizer(_:)))
self.lbMail.isUserInteractionEnabled = true
self.lbMail.addGestureRecognizer(lbAddressTap2)
let lbAddressTap3 = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressReconizer(_:)))
self.lbPhone.isUserInteractionEnabled = true
self.lbPhone.addGestureRecognizer(lbAddressTap3)
}
#objc func longPressReconizer(_ sender: UITapGestureRecognizer) {
print("labelTapped")
let etichetta :UILabel = sender.view as! UILabel
print (etichetta.text!)
switch etichetta.tag {
case 0:
self.performSegue(withIdentifier: "moveToMaps", sender: self)
case 1:
let telNumber = etichetta.text!.replacingOccurrences(of: " ", with: "")
if let phoneCallURL = URL(string: "telprompt://\(telNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
}
}
case 2:
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([etichetta.text!])
mail.setSubject("Informazioni")
self.window?.rootViewController?.present(mail, animated: true)
} else {
// show failure alert
}
default:
print("default")
}
}
func mailComposeController(_ controller:MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
but Xcode give me this error
Value of type 'OfficeCell' has no member 'performSegue'
on
self.performSegue(withIdentifier: "moveToMaps", sender: self)
how to achieve what i need ?
Thanks in advance
Fabrizio
you need to implement delegate and perform segue from main class because cell class can't perform segue ... in storyBoard attach "moveToMaps" segue from main controller
protocol CellDelegate {
func didTapAddressButton()
}
class OfficeCell: UITableViewCell, MFMailComposeViewControllerDelegate {
var delegate: CellDelegate?
}
In your main View controller class
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OfficeCell", for: indexPath) as! OfficeCell
cell.delegate = self
return cell
}
extension MainController: CellDelegate {
func didTapAddressButton(){
self.performSegue(withIdentifier: "moveToMaps", sender: self)
}
}

Error in Table View Controller When using a segue Fatal error: Index out of range

I've ran into a problem and i cant resolve it
TableViewController:
var items: [String?] = ["door","table","chair"]
var givenDescription: [String?] = ["Change the description using
class TableViewController: UITableViewController, UIToolbarDelegate {
the edit option"]
#IBOutlet var myTableView: UITableView!
override func viewDidAppear(_ animated: Bool) {
myTableView.reloadData()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = items[indexPath.row]
cell.detailTextLabel?.text = givenDescription[indexPath.row]
return cell
}
ViewController:
import UIKit
import MobileCoreServices
class AddViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var newPic: Bool?
//Outlets
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var addName: UITextField!
#IBOutlet weak var addDescription: UITextField!
#IBAction func addImage(_ sender: Any) {
let myAlert = UIAlertController(title: "Select Image From", message: "", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: nil)
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
self.newPic = true
}
let cameraRoll = UIAlertAction(title: "Camera Roll", style: .default, handler: nil)
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
self.newPic = false
}
myAlert.addAction(cameraAction)
myAlert.addAction(cameraRoll)
self.present(myAlert, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
if newPic == true {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(imageError), nil)
}
}
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
#objc func imageError(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafeRawPointer) {
if error != nil {
let alert = UIAlertController(title: "Save Failed", message: "Failed to save image", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Okay", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
//Action
#IBAction func create(_ sender: Any) {
if (addName.text != "") {
items.append(addName.text!)
addName.text = ""
}
if (addDescription.text != "") {
givenDescription.append(addDescription.text!)
addDescription.text = ""
}
self.navigationController?.popViewController(animated: true)
}
}
You can "fix" the create function in several ways, for example like this:
#IBAction func create(_ sender: Any) {
if (addName.text != "" && addDescription.text != "") {
items.append(addName.text!)
addName.text = ""
givenDescription.append(addDescription.text!)
addDescription.text = ""
}
self.navigationController?.popViewController(animated: true)
}
but a much better option is to create a simple struct
struct Item {
var name: String
var itemDescription: String
}
and use it instead
#IBAction func create(_ sender: Any) {
if (addName.text != "" && addDescription.text != "") { //or just check one depending on if one is more important
let item = Item(name: addName.text!, itemDescription: addDescription.text!)
items.append(item)
}
self.navigationController?.popViewController(animated: true)
}
and the items array is defined as
var items: [Item]()
andd for your table view
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
let item = items[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = item.itemDescription
return cell
}
This was the answer so simple.
#IBAction func create(_ sender: Any) {
if (addName.text != "" && addDescription.text != "") {
items.append(addName.text!)
addName.text = ""
givenDescription.append(addDescription.text!)
addDescription.text = ""
}
self.navigationController?.popViewController(animated: true)
}

How can I save multiple images which are picked from the UIPickerController?

All the images which I'm uploading in the app (with the UIImagePickerController) are showing in the app but when I'm closing the app the images disappear. I used UserDefaults for one image (without the UICollectionView) and the code worked (see the code) but when i used the UICollectionView, the code does not work anymore. It would be nice if anyone can help me or give me some tips!
import UIKit
class wardrobeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var allImagesCollection: UICollectionView!
var collectionViewClass = CollectionViewCell()
var theUploadedImg = UIImageView()
let userDefault = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
allImagesCollection.delegate = self
allImagesCollection.dataSource = self
collectionViewClass.newImage = theUploadedImg
let imageData = userDefault.object(forKey: "thePickedImage") as? NSData
if let imageData = imageData {
let image = UIImage(data: imageData as Data)
theUploadedImg.image = image
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func chooseImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "", message: "Choose an image from", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
imagePickerController.allowsEditing = false
self.present(imagePickerController, animated: true, completion: nil)
}
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePickerController.allowsEditing = false
self.present(imagePickerController, animated: true, completion: nil)
}
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
var newPickedImage = [UIImage]()
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
theUploadedImg.contentMode = .scaleToFill
theUploadedImg.image = pickedImage
newPickedImage.append(pickedImage)
let pickedImageData = UIImagePNGRepresentation(pickedImage)
userDefault.set(pickedImageData, forKey: "thePickedImage")
}
picker.dismiss(animated: true, completion: nil)
allImagesCollection.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return newPickedImage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.newImage.image = newPickedImage[indexPath.item]
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 0.5
return cell
}
let cellsPerRow = 3
override func viewWillLayoutSubviews() {
guard let collectionView = allImagesCollection, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + flowLayout.minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
}
You are saving only 1 image to UserDefaults. In order to persist these images, you have to save all of them, not just override 1 image. Also, on application start you have to fetch all of the images and reload UICollectionView with them.
One more tip, do not save images to UserDefaults, use FileManager.

Adding Photos to Array and Displaying to UICollection View error

QUESTION
This code works to set an image to an array but comes up with the following error - 2017-12-06 12:31:21.264812+0000 SmartReceipts[880:172369] [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
I need to know what this means and if there is a possible fix around it?
import UIKit
class GalleryController: UICollectionViewController,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
var Receipts = [UIImage?]()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.reloadData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
//self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
print(info);
let newReceipts = info[UIImagePickerControllerEditedImage] as? UIImage
self.Receipts.append(newReceipts)
print("Array Contains \(self.Receipts.count) Receipts")
print(self.Receipts)
self.collectionView?.reloadData()
print("completedIfStatement")
}
#IBAction func getReceipts(_ sender: Any) {
print("PlusButtonPressed")
let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)
// 2
let albumAction = UIAlertAction(title: "Album", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("PhotosOption")
self.getFromReceipts()
})
let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("CameraOption")
self.getFromCamera()
})
//
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// 4
optionMenu.addAction(albumAction)
optionMenu.addAction(cameraAction)
optionMenu.addAction(cancelAction)
// 5
self.present(optionMenu, animated: true, completion: nil)
}
func getFromReceipts() {
print("GetFromReceipts")
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .photoLibrary
self.present(cameraPicker, animated: true, completion: nil )
}
func getFromCamera() {
print("GetFromCamera")
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
self.present(cameraPicker, animated: true, completion: nil )
}
//Number of Views
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.Receipts.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Receipts, for: indexPath as IndexPath) as? PhotoCell
cell?.imageView.image = self.Receipts[indexPath.row]
return cell!
}
}
The error maybe comes from not requesting the authorization to load an photo from the camera or the photo library. So you need to request for authorization before opening the camera like:
https://developer.apple.com/documentation/photos/phphotolibrary/1620736-requestauthorization
I guess you'r not requesting Photo/Camera authorizations.
You have to add the below keys to Info.plist.
Camera permission :
<key>NSCameraUsageDescription</key>
<string> ${PRODUCT_NAME} Camera Usage< </string>
For Photo Library, you will want this one to allow app user to browse the photo library.
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} Photo Usage</string>
And in you'r source code, to ask permission for the photo/camera you need to add this code (Swift 3):
PHPhotoLibrary.requestAuthorization({
(newStatus) in
if newStatus == PHAuthorizationStatus.authorized {
/* do stuff here */
}
})

Swift UIButton background image not being set by UIImagePicker

I am able to select an Image from the PhotoLibrary but the background image of my UIButton does not change. The println in didFinishPickingImage and imagePickerControllerDidCancel does not show in the console so I do not think those functions are being called.
class AddTeamTableViewController: UITableViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIAlertViewDelegate {
var picker:UIImagePickerController? = UIImagePickerController()
#IBOutlet var teamNumber: UITextField!
#IBOutlet var schoolName: UITextField!
#IBOutlet var teamImage: UIButton!
#IBAction func cancelButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func addTeam(sender: AnyObject) {
var newTeam = Team()
var onlineTeam = PFObject(className: "Team")
// add new team to the list
newTeam.name = teamNumber.text
newTeam.schoolName = schoolName.text
teamList.append(newTeam)
// add online
onlineTeam["name"] = newTeam.name
onlineTeam["fromUser"] = PFUser.currentUser()
onlineTeam["schoolName"] = newTeam.schoolName
onlineTeam.save()
//close the view
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 1
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
#IBAction func pickImage(sender: AnyObject) {
var image = UIImagePickerController()
image.delegate = self
var alert:UIAlertController = UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.openCamera()
}
var galleryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.openGallery()
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
}
alert.addAction(cameraAction)
alert.addAction(galleryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
/*
alert.delegate = self
alert.message = "Choose Image Source"
alert.addButtonWithTitle("Camera")
alert.addButtonWithTitle("Photo Library")
alert.show()
*/
//image.sourceType = UIImagePickerControllerSourceType.Camera
//image.allowsEditing = false
//self.presentViewController(image, animated: true, completion: nil)
}
func openCamera() {
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
picker!.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(picker!, animated: true, completion: nil)
} else {
openGallery()
}
}
func openGallery() {
picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(picker!, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
println("Image selected")
self.dismissViewControllerAnimated(true, completion: nil)
teamImage.setBackgroundImage(image, forState: UIControlState.Normal)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!) {
println("picker cancel")
}
}
The button doesn't seem initialized
let teamImage: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 380, height: 300))
let imageTest = UIImage(named: "Hypnotoad")
teamImage.setTitle("HypnotoadTitle", forState: .Normal)
teamImage.setBackgroundImage(imageTest, forState: .Normal)
tested this in a Playground and works ok.
I figured it out. I had 2 different variables of type UIImagePickerController and I was saving to the wrong one. I deleted the first var picker declaration and combined the code to just one UIImagePickerController and it works as intended.