将UIImage传递给另一个视图控制器的单元格

时间:2015-11-26 16:45:05

标签: ios swift

我正在尝试将UIImage()变量的内容传递给下一个View Controller的Cell。

基本上我的布局如下:

图像将加载到ControllerA中,然后保存在模型中。

在下一个控制器中,加载了一个TableViewCell。

我希望图片加载到单元格内。

我如何实现这一目标?

我的代码:

第一部分:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    // Save the poem.
    savePoem()
}

func savePoem() {
    // Save the poem current completion date.
    poem.date = NSDate()

    // Save the theme name for the poem.
    poem.theme = theme.name

    // Save the currently displayed picture.
    poem.image = ImageView.image

    poem.words = textField.words

    // Make the poem object persist.
    PoemPersistence.sharedInstance.persistPoem(poem)
}

单元格加载图片:

func configureWithPoem(poem: Poem) {
    themeLabel.text = "#\(poem.theme)"
    poemLabel.text = poem.words
    pictureImageView.image = poem.image
}

func capturePoemImage() -> UIImage {
    // Hide the share button.
    shareButton.hidden = true

    // Capture a PNG of the view.
    UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
    layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let containerViewImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Show the share button.
    shareButton.hidden = false

    return containerViewImage
}

单元格被加载到第二个控制器中:

func poemCellWantsToSharePoem(poemCell: PoemCell) {
    // Find the poem displayed at this index path.
    let indexPath = tableView.mp_indexPathForCell(poemCell)
    let poem = poems[indexPath.row]

    // Generate the image of the poem.
    let poemImage = poemCell.capturePoemImage()

1 个答案:

答案 0 :(得分:0)

如果您只想使用prepareForSegue()将数据发送到下一个UIViewController - 创建segue到下一个控制器(control + Drag),然后给标识符命名。

  • 现在通过声明

    来设置目标控制器
     @IBOutlet weak var imageView:UIImageView!
        var image:String ?
    override func viewDidLoad()
    {
       imageView.image = image    
    }
    

    此图像变量将接收数据,然后将其分配给@IBOutlet。

     func prepareForSegue (segue:UIStoryboardSegue, sender:AnyObject?) 
      {
    
             if  segue.identifier ==   "NAMEOFSEGUEIDENTIFIER"
            {
                let destinationController = segue.destinationViewController as! NAMEOFTHEDESTIONCONTROLLER
                let indexPath = tableView.indexPathForSelectedRow!
          // now the data structure that contains your information, use it there
                let data = dataContainer[indexPath.row]
    
           // i noticed that you might be using struct so 
           // let's passed the picture from that specific row to the next conroller 
           destinationController.image = data.image
           } 
      }
    

我希望有帮助:)