Loading image to Image Cell from URL

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 04:48:46

问题


I'm learning to code in swift. I'm trying to load an image onto an image cell located within an image well.I'm using the following code

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var well: NSImageCell!
    @IBAction func clickme(_ sender: Any) {
    let image = NSImage(byReferencing:NSURL(string: "http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg")! as URL)
        well.image=image;
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

No exception is thrown nor any image is loaded. What I'm I doing wrong?


回答1:


Try this.

Simple Way.

let url = NSURL(string:"your url")
        let imagedata = NSData.init(contentsOf: url! as URL)

        if imagedata != nil {
            imageView.image = UIImage(data:imagedata! as Data)
        }

Create extension.

   extension UIImageView{

        func setImageFromURl(ImageUrl: String){

            if let url = NSURL(string: ImageUrl) {
                if let imagedata = NSData(contentsOf: url as URL) {
                    self.image = UIImage(data: imagedata as Data)
                }
            }
        }
    }

 //Use this extension

    imageView.setImageFromURl(ImageUrl: "your url")

Use AFNetworking.

//without placeholder
    imageView.setImageWith(URL.init(string: "your url")!)
//with placeholder
    imageView.setImageWith(URL.init(string: "your url")!, placeholderImage: UIImage.init(named: "placeholder.png"))

Use SDWebImage.

imageView.sd_setImage(with: URL(string: "your url"), placeholderImage: UIImage(named: "placeholder.png"))


来源:https://stackoverflow.com/questions/46176409/loading-image-to-image-cell-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!