2016-10-05 4 views
0

Я пытаюсь выяснить способ загрузки изображений, загружаемых через SDWebImage в TableView, в представление (DetailView), где изображение можно просмотреть в полноэкранном режиме.Как вывести изображения SDWebImage в подробный вид

У меня есть изображения, загруженные из URL-адресов, отображаемых на виде таблицы правильно. Но когда я нажимаю один, он переходит к другому представлению (DetailView), которое пустое, когда у меня есть UIImage. По какой-то причине изображение не загружается.

Спасибо!

Вот код TableView:

import UIKit 

class TableViewController: UITableViewController { 

var imageURLs = [String]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    imageURLs = ["https://i.imgur.com/lssFB4s.jpg","https://i.imgur.com/bSfVe7l.jpg","https://i.imgur.com/vRhhNFj.jpg"] 


    // 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. 

} 

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

    if (segue.identifier == "DetailView") { 

     let VC = segue.destinationViewController as! DetailViewController 
     if let indexpath = self.tableView.indexPathForSelectedRow { 

      let Imageview = imageURLs[indexpath.row] as String 
      VC.SentData1 = Imageview 
     } 

    } 



} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") 

    let cell2: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell 

    let imagename = UIImage(named: imageURLs[indexPath.row]) 
    cell2.cellImage.image = imagename 


    let imageView = cell?.viewWithTag(1) as! UIImageView 

    imageView.sd_setImage(with: URL(string: imageURLs[indexPath.row])) 

    return cell! 


} 

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

Вот код DetailView:

import UIKit 

class DetailViewController: UIViewController { 

@IBOutlet weak var Detailimageview: UIImageView! 

var SentData1:String! 


override func viewDidLoad() { 
    super.viewDidLoad() 


    Detailimageview.image = UIImage(named: SentData1) 


    // 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: AnyObject?) { 
    // Get the new view controller using segue.destinationViewController. 
    // Pass the selected object to the new view controller. 
} 
*/ 

ответ

1

Вы используете UIImage(named:) в пункт назначения VC. Это попытается загрузить изображение из вашего пакета, а не из сети. Вы должны использовать sd_setImage для извлечения его из сети (или через кэш, если он уже был извлечен):

Detailimageview.sd_setImage(with: URL(string:self.SentData1)) 

Обратите внимание, что свойства и переменные должны начинаться с прописной буквой по соглашению

+0

Спасибо за ответ. Я получаю сообщение об ошибке: Значение типа 'UIImage?' не имеет ни один из членов «sd_setImage» Чтобы было ясно, я наклеивать его на: Detailimageview.image = UIImage (названный: SentData1) Означает ли эта ошибка SDWebImage не был «загружен» на DetailViewController? Спасибо! – Miles

+0

К сожалению, это была опечатка. Исправлено: – Paulw11

+0

Все отлично! Большое вам спасибо, оцените! – Miles

0

При загрузке ваш подробный вид, вы передаете URL-адрес веб-сайта для изображения, которое хотите загрузить, но затем пытаетесь загрузить его из пакета с помощью UIImage(named: SentData1).

Вместо этого вы должны просто нагружать его так же, как вы делаете это в вашем Tableview клеток, делая что-то вроде Detailimageview.sd_setImage(with: URL(string: SentData1))

+0

Спасибо за ваш ответ. Я получаю сообщение об ошибке: Значение типа 'UIImage?' не имеет члена 'sd_setImage' Чтобы быть ясным, я вставляю его: Detailimageview.image = UIImage (named: SentData1) Означает ли это, что SDWebImage не был «загружен» в DetailViewController? Спасибо! – Miles

+0

Я не вижу, как вы получите эту ошибку с кодом, который я вам дал. Вы уверены, что не сделали что-то еще? – Dima

+0

Paulw11 ответил ниже с немного другой строкой кода: Detailimageview.sd_setImage (с: URL (строка: self.SentData1)) Кажется, что это работает. Я ценю помощь! – Miles

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