1

I have a UIImageView (0x0) in my NewsTableViewController.swift which segues to NewsDetailTableViewController.swift where the UIImageView is 600x216.

If you ask why the first UIImageView is 0x0, it is because it is the only way that I know how to segue a different image by each cell. I have 16 cells in my main VC and a different image for each detail VC. I don't want to display the image in the main VC's cell.

If you could suggest another way, that would be great.

Anyway, keeping with this solution, what is the problem with my segue? The images are stored in an array called detailImages. This array is in NewsTableViewController.swift.

Here is my NewsDetailTableViewController.swift:

The UIImageView should be where the white space between the title and content is.

Here is my prepareForSegue method in my NewsTableViewController.swift:

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

    if segue.identifier == "showDetail" {

        if let indexPath = tableView.indexPathForSelectedRow {
            let destinationController = segue.destinationViewController as! NewsDetailTableViewController
            destinationController.item = items[indexPath.row]
            //destinationController.imageNames = detailImages
        }
    }
}

Here is my NewsDetailTableViewController.swift code:

import UIKit

class NewsDetailTableViewController: UITableViewController {

var items = [Item]()
var item:Item!
var siteURL = "http://annabellesykes.netau.net/shailenewoodleyfansappjson.json"
var image:UIImageView!
@IBOutlet weak var segueImageView:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    title = "News"
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
    getLatestNews()

    tableView.estimatedRowHeight = 400.0
    tableView.rowHeight = UITableViewAutomaticDimension

    tableView.separatorStyle = UITableViewCellSeparatorStyle.None


}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewsDetailTableViewCell

    // Configure the cell...
    cell.newsDetailTitle.text = item.title
    cell.newsDetailDate.text = item.date
    cell.newsDetailContent.text = item.content
    cell.newsDetailImageView.image = UIImage()

    cell.newsDetailTitle.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.newsDetailTitle.numberOfLines = 999
    cell.newsDetailContent.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.newsDetailContent.numberOfLines = 999

    cell.newsDetailTitle.sizeToFit()
    cell.newsDetailContent.sizeToFit()

    return cell
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func getLatestNews() {

    let request = NSURLRequest(URL: NSURL(string: siteURL)!)
    let urlSession = NSURLSession.sharedSession()
    let task = urlSession.dataTaskWithRequest(request, completionHandler: {
        (data, response, error) -> Void in

        if let error = error {
            print(error)
            return
        }

        if let data = data {
            self.items = self.parseJsonData(data)

            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.tableView.reloadData()
            })
        }

    })

    task.resume()
}

func parseJsonData(data: NSData) -> [Item] {

    var items = [Item]()

    do {

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

        let jsonItems = jsonResult?["items"] as! [AnyObject]
        for jsonItem in jsonItems {
            let item = Item()
            item.title = jsonItem["title"] as! String
            item.content = jsonItem["content"] as! String
            item.date = jsonItem["date"] as! String
            items.append(item)
        }

    } catch {
        print(error)
    }

    return items
}


}

Here is my NewsTableViewController.swift:

import UIKit

class NewsTableViewController: UITableViewController {

var siteURL = "http://annabellesykes.netau.net/shailenewoodleyfansappjson.json"
var items = [Item]()
var item:Item!
var newsImage:UIImageView?

@IBOutlet weak var imageHeaderView1:UIImageView!

var detailImages = ["newsimage1.jpg", "newsimage2.jpg", "newsimage3.jpg", "newsimage4.jpg", "newsimage5.jpg", "newsimage6.jpg", "newsimage7.jpg", "newsimage8.jpg", "newsimage9.jpg", "newsimage10.jpg", "newsimage10.jpg", "newsimage11.jpg", "newsimage12.jpg", "newsimage13.jpg", "newsimage14.jpg", "newsimage15.jpg", "newsimage16.jpg"]

override func viewDidLoad() {
    super.viewDidLoad()

    getLatestNews()
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewsTableViewCell

    // Configure the cell...
    cell.titleLabel.text = items[indexPath.row].title
    cell.dateLabel.text = items[indexPath.row].date
    cell.contentLabel.text = items[indexPath.row].content
    cell.newsImageView.image = UIImage(named: detailImages[indexPath.row])

    cell.titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.titleLabel.numberOfLines = 999
    cell.contentLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.contentLabel.numberOfLines = 3
    cell.dateLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.dateLabel.numberOfLines = 999

    cell.dateLabel.sizeToFit()

    //cell.imageView?.image = self.imageNames[indexPath.row]

    return cell
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction] {

    let shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler: { (action, indexPath) -> Void in

        let defaultText = "Check this out: " + self.items[indexPath.row].title + "! " + self.items[indexPath.row].content
        let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)
        self.presentViewController(activityController, animated: true, completion: nil)
    })

    shareAction.backgroundColor = UIColor(red: 179.0/255.0, green: 239.0/255.0, blue:  247.0/255.0, alpha: 1.0)

    return [shareAction]
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
    cell.alpha = 0
    UIView.animateWithDuration(1.0, animations: { cell.alpha = 1 })
}

func getLatestNews() {

    let request = NSURLRequest(URL: NSURL(string: siteURL)!)
    let urlSession = NSURLSession.sharedSession()
    let task = urlSession.dataTaskWithRequest(request, completionHandler: {
        (data, response, error) -> Void in

        if let error = error {
            print(error)
            return
        }

        if let data = data {
            self.items = self.parseJsonData(data)

            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.tableView.reloadData()
            })
        }

    })

    task.resume()
}

func parseJsonData(data: NSData) -> [Item] {

    var items = [Item]()

    do {

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

        let jsonItems = jsonResult?["items"] as! [AnyObject]
        for jsonItem in jsonItems {
            let item = Item()
            item.title = jsonItem["title"] as! String
            item.content = jsonItem["content"] as! String
            item.date = jsonItem["date"] as! String
            items.append(item)
        }

    } catch {
        print(error)
    }

    return items
}

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

    if segue.identifier == "showDetail" {

        if let indexPath = tableView.indexPathForSelectedRow {
            let destinationController = segue.destinationViewController as! NewsDetailTableViewController
            destinationController.item = items[indexPath.row]
            destinationController.image = UIImageView(image: UIImage(named: detailImages[indexPath.row]))
        }
    }
}

@IBAction func unwindToHomeScreen(segue: UIStoryboardSegue) {
}

}
Annabelle Sykes
  • 263
  • 6
  • 17

2 Answers2

0

You don't seem to be setting your image properly in cellForRowAtIndexPath in your NewsDetailTableViewController.swift.

This line in particular:

cell.newsDetailImageView.image = UIImage()

Robin Dorpe
  • 344
  • 3
  • 7
  • What shall I do with this line? – Annabelle Sykes Feb 16 '16 at 11:28
  • This is where you should set your image, using the content of `detailImages`. But looking at your code it seems like you don't have an array called `detailImages` in `NewsDetailTableViewController.swift`. Where is the image that you want to display stored? – Robin Dorpe Feb 16 '16 at 11:34
  • It's stored in `NewsTableViewController.swift`. – Annabelle Sykes Feb 16 '16 at 15:44
  • Ok, my bad. So you have an array of images and you want to pass a specific one to `NewsDetailTableViewController.swift`. I suppose you could create a `UIImage` variable on `NewsDetailTableViewController.swift` and set it in `prepareForSegue`. I assume the value would be `detailImages[indexPath.row]`. – Robin Dorpe Feb 16 '16 at 15:57
  • How would I write this? Like `destinationController.image = UIImage(named: detailImages[indexPath.row])`? – Annabelle Sykes Feb 16 '16 at 15:58
  • I did `destinationController.image = UIImageView(image: UIImage(named: detailImages[indexPath.row]))`, but the image did not show up. – Annabelle Sykes Feb 16 '16 at 16:01
  • in `detailImages` do you store the name of the images or the images themselves? If names only, then what you wrote (`destinationController.image = UIImage(named: detailImages[indexPath.row])`) is correct, except you have to make sure that image is a `UIImage` and not `UIImageView`. If you store the images, then you need `destinationController.image = detailImages[indexPath.row]`, here again, make sure image is a `UIImage`. Then replace `cell.newsDetailImageView.image = UIImage()` with `cell.newsDetailImageView.image = image` – Robin Dorpe Feb 16 '16 at 16:06
  • I store the image name in an array, with the images in Xcassets.assets, but `destinationController.image = UIImage(named: detailImages[indexPath.row])` does not show the image in the simulator. – Annabelle Sykes Feb 16 '16 at 16:10
  • replace `var image:UIImageView!` with `var image: UIImage?`. And replace `cell.newsDetailImageView.image = UIImage()` with `cell.newsDetailImageView.image = image`. Also, make sure that `detailImages[indexPath.row]` returns an actual image name. – Robin Dorpe Feb 16 '16 at 16:21
  • When I add this, this line in the `prepareForSegue` method comes up with the error 'inout [String]' (aka 'inout Array') is not convertible to 'Array': `destinationController.image = UIImageView(image: UIImage(named: detailImages[indexPath.row]))` – Annabelle Sykes Feb 18 '16 at 10:25
  • The problem seems to come from elsewhere, could you share more code? I need to see `NewsTableViewController.swift` in particular. – Robin Dorpe Feb 18 '16 at 11:26
  • Okay, I'll add it now. – Annabelle Sykes Feb 18 '16 at 12:12
  • replace `destinationController.image = UIImageView(image: UIImage(named: detailImages[indexPath.row]))` with `destinationController.image = UIImage(named: detailImages[indexPath.row])` and make sure `image` in NewsDetailTableViewController.swift is a UIImage and not UIImageView – Robin Dorpe Feb 18 '16 at 15:10
  • I'll come back to you when my simulator is back up and running, it's having errors at the moment. – Annabelle Sykes Feb 18 '16 at 15:12
  • Perfect! It works now! I just want to personally thank you for sticking with me for these days. Most people on this website just leave you, especially newbies and youngsters, so thank you so much, I really appreciate this! – Annabelle Sykes Feb 18 '16 at 15:23
  • No problems, glad I could help. Please accept the answer if it solved your issue. Good luck on your app. – Robin Dorpe Feb 18 '16 at 16:18
-2
Here is code in objective c... 
#pragma Mark Prepare For Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"segue"]) {

    viewcontroller *destViewController = segue.destinationViewController;
        destViewController.image=[[Apparels objectAtIndex:0];

        }
}

//In other class 
@property (strong, nonatomic) NSString *image;
   UIImageView.image=[UIImage imageNamed:image];
Sabby
  • 403
  • 3
  • 15