Swift 4.我所做的非常简单的项目-只是以编程方式从.jpg文件中添加了NSImageView
和backgroundColor
。我看到了很好的粉红色,但根本看不到图像!我尝试了许多不同的方法,但有些方法是成功的(图像在集合视图中显示良好,并且如果在故事板上手动添加了NSImage
),但是我需要一种简单的编程方法。这是我所有的代码:
NSImageView
非常感谢...
---已编辑---
是的,谢谢!刚刚添加并看到图片:
class ViewController: NSViewController {
var image: NSImage = NSImage()
var ivTest = NSImageView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.ivTest)
self.ivTest.wantsLayer = true
self.ivTest.layer?.backgroundColor = NSColor.systemPink.cgColor
self.ivTest.layer?.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
let manager = FileManager.default
var url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
url = url?.appendingPathComponent("night.jpg")
image = NSImage(byReferencing: url!)
if (image.isValid == true){
print("valid")
print("image size \(image.size.width):\(image.size.height)")
self.ivTest.image = image
} else {
print("not valid")
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}