2015-11-02 2 views
0

Я 2 VC:Проблема с Segue изображения к другому ViewController

Первый VC с 1 кнопка при постукивании >> 2 варианта после формы изображения кулачковый или библиотека

Второй VCвыбранное изображение форма VC1, отведенная ко второму VC

Я попытался понять Это ошибка без каких-либо s uccess

fatal error: unexpectedly found nil while unwrapping an Optional value pointed at

imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage 

Я загрузил проект в раздаточной https://www.dropbox.com/s/w7blbnyac9qyxgw/segImage.zip?dl=0

VC1

class ViewController:UIViewController,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPopoverControllerDelegate 
{ 
    @IBOutlet weak var btnClickMe: UIButton! 
    @IBOutlet weak var imageView: UIImageView! 
    var picker:UIImagePickerController?=UIImagePickerController() 
    var popover:UIPopoverController?=nil 

    override func viewDidLoad() 
    { 
     super.viewDidLoad() 
     picker!.delegate=self 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 



    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     if (segue.identifier == "") { 
      let destVC : second = segue.destinationViewController as! second 
      destVC.pics = imageView.image! 
     } 
    } 

    @IBAction func btnImagePickerClicked(sender: AnyObject) 
    { 
     let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) 

     let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) 
      { 
       UIAlertAction in 
       self.openCamera() 

     } 
     let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default) 
      { 
       UIAlertAction in 
       self.openGallary() 
     } 
     let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) 
      { 
       UIAlertAction in 

     } 

     // Add the actions 
     picker?.delegate = self 
     alert.addAction(cameraAction) 
     alert.addAction(gallaryAction) 
     alert.addAction(cancelAction) 
     // Present the controller 
     if UIDevice.currentDevice().userInterfaceIdiom == .Phone 
     { 
      self.presentViewController(alert, animated: true, completion: nil) 
     } 
     else 
     { 
      popover=UIPopoverController(contentViewController: alert) 
      popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) 
     } 
    } 
    func openCamera() 
    { 
     if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) 
     { 
      picker!.sourceType = UIImagePickerControllerSourceType.Camera 
      self .presentViewController(picker!, animated: true, completion: nil) 
     } 
     else 
     { 
      openGallary() 
     } 
    } 
    func openGallary() 
    { 
     picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary 
     if UIDevice.currentDevice().userInterfaceIdiom == .Phone 
     { 
      self.presentViewController(picker!, animated: true, completion: nil) 
     } 
     else 
     { 
      popover=UIPopoverController(contentViewController: picker!) 
      popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) 
     } 
    } 
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) 
    { 
     picker .dismissViewControllerAnimated(true, completion: nil) 
     imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage 
    } 
    func imagePickerControllerDidCancel(picker: UIImagePickerController) 
    { 
     print("picker cancel.") 
    } 


} 

второй VC

class second: UIViewController { 

var pics = UIImage() 

@IBOutlet var image: UIImageView! 
override func viewDidLoad() { 
    super.viewDidLoad() 

    if let img = UIImage(named: "pics") 
    { 
     self.image.image = img 
    } 
} 

ответ

1

раскадровки проводка неправильно.

Изображение должно действительно быть установлен на экземпляре second, а не экземпляр ViewController. Обратите внимание, что авария происходит в ViewController и не second

Этот код:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) 
{ 
    picker .dismissViewControllerAnimated(true, completion: nil) 
    imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage 
} 

пытается установить a imageView.image в ViewController. Если вы посмотрите на раскадровку, то UIImageView в ViewController.

enter image description here

То, как вы определили imageView на ViewController, что делает этот крах:

@IBOutlet weak var imageView: UIImageView! 

с ! там, вы говорите: «Это никогда не будет равна нулю.» Ну, это, очевидно, не так, потому что, поскольку этот IBOutlet не подключен к UIImageView, тогда он равен нулю. И таким образом, когда вы пытаетесь получить к нему доступ, BOOM!

Чтобы это исправить:

  • Segue к second, когда пользователь выбирает снимок на
  • Установить выбранное изображение на second «s image.imageView свойство

Другое предложение: - Используйте последовательность в именования, например, второй против SecondViewController

Смежные вопросы