问题
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