如何将图像添加到 UIImageView?

How to add image to UIImageView?

我正在尝试将图像添加到 UIImageView,但在我添加之后 UIImageView 为零。这是我的代码:

    class ViewController: UIViewController {

    @IBOutlet var myView: UIView!
    @IBOutlet weak var testImg: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        UIGraphicsBeginImageContext(CGSize(width: 500,height: 500))
                var path = UIBezierPath()
        path.lineWidth = 1.0
        path.moveToPoint(CGPoint(x: 150, y: 150))
        var x = 151
        for ;x<300;x++
        {
            path.addLineToPoint(CGPoint(x: x, y: x))
            path.moveToPoint(CGPoint(x: x, y: x))
        }
        path.stroke()
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
                testImg = UIImageView(image: img)
        testImg.frame = CGRect(x: 0,y: 0,width: 500,height: 500)
        myView.addSubview(testImg)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

当我尝试为 UIImageView 设置框架时,出现此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

可能是我没有正确创建图像。

更新

testImg = UIImageView(image: img)

这行代码覆盖了UIImageViewIBOutlet,删除它并简单地做 testImg.image = img 修复问题。

简单方法:将该图像拖放到 Xcode 上的文件 view/project 导航器中。

Select 图像视图 - 然后属性检查 - 在图像下 - Select 您要加载的图像的文件名。

尽可能享受拖放。

硬道:

if let filePath = Bundle.main.path(forResource: "imageName", ofType:     "jpg"), let image = UIImage(contentsOfFile: filePath) {    imageView.contentMode = .scaleAspectFit
    imageView.image = image
}

错误应该与您推送或呈现 ViewController 的方式有关。当您展示或展示插座时,插座似乎尚未创建。应该使用 instantiateViewControllerWithIdentifier 如下例

let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("YourStoryBoardId")
self.navigationController?.pushViewController(viewController!, animated: true)

简单:

if let image = img {
    // you don't have to instantiate an imageView again, IBOutlet handles it for you    
    testImg.image = image
    print("Works")
    // if you don't see this output in your debug console, the condition never succeeds and an img is really nil
}