我正在学习快速编码。 我试图将图像加载到位于图像中的图像单元格中。我使用以下代码
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.
}
}
}
不会抛出任何异常,也不会加载任何图像。 我做错了什么?
答案 0 :(得分:4)
试试这个。
简单的方法。
let url = NSURL(string:"your url")
let imagedata = NSData.init(contentsOf: url! as URL)
if imagedata != nil {
imageView.image = UIImage(data:imagedata! as Data)
}
创建扩展程序。
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")
使用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"))
使用SDWebImage。
imageView.sd_setImage(with: URL(string: "your url"), placeholderImage: UIImage(named: "placeholder.png"))