这是我的代码,请帮助,我正在按照教程,但我无法弄清楚什么是错的。请帮忙。
我试图制作如果选择了图像,然后执行segue到另一个视图控制器并显示之前选择的图像
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("showImage", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "showImage"
{
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
let vc = segue.destinationViewController as! SecondViewController
vc.image = self.url[indexPath.row] //Error Cannot Assign a value of type 'String' to type 'UIImage'
}
}
我会感谢你的帮助。
答案 0 :(得分:2)
vc.image = self.url[indexPath.row]
,您将indexPath.row作为字符串,您必须在self.url["here"]
内使用UIImage(named:"imagename")
内的字符串中的图像获取所有self.url[UIImage(named:indexPath.row)
}
并且视图控制器vc应该具有UIImage类型的图像变量。
答案 1 :(得分:1)
self.url [indexPath.row] 给出一个字符串值,您无法直接将字符串分配给图像,这就是为什么它会抛出错误无法分配类型的值'字符串'输入' UIImage'
因此,您必须将其转换为数据,如下所示。例如
let ImageView = UIImageView()
let data = NSData(contentsOfURL: NSURL(string: "http://www.macmillandictionaryblog.com/wp-content/uploads/2011/07/Small-Talk-image.jpg")!)
ImageView.image = UIImage(data: data!)
在您的情况下,以下代码可能会有所帮助,我认为 Self.url 是一个包含图片网址的数组
if segue.identifier == "showImage"
{
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
let vc = segue.destinationViewController as! SecondViewController
let URLStr = self.url[indexPath.row] as! String
let data = NSData(contentsOfURL: NSURL(string: URLStr)!)
vc.image.image = UIImage(data: data!) //Now it will work if vc.image is an UIImageView
}
答案 2 :(得分:0)
使用此代码在Swift4中可以正常工作
let subCategory = tableData[indexPath.row]
let urlString = "https://www.youtube.com/"
print(urlString)
let url = URL(string: urlString!)
let data = try? Data(contentsOf: url!)
if let imageData = data {
let image = UIImage(data: imageData)
cell?.userPicImage.image = image
}else {
cell?.userPicImage.image = UIImage(named: "SomeEmptyImage")
}
答案 3 :(得分:0)
这很简单
let url = NSURL(string:"<image url>")
let imagedata = NSData.init(contentsOf: url! as URL)
if imagedata != nil {
cell.imageView.image = UIImage(data:imagedata! as Data)
}