2017-10-13 127 views
-3

我來到這裏這樣的錯誤:導航欄圖片

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

什麼是錯我的代碼?我嘗試將圖像添加到navcontroller,我可以在這裏看到圖像。

func addNavBarImage() { 
    let nc = navigationController! 
    let image = UIImage(named: "2.png") 
    let imageView = UIImageView(image: image) 

    let bwidth = nc.navigationBar.frame.size.width 
    let bheight = nc.navigationBar.frame.size.height 

    let bannerx = bwidth/2 - (image?.size.width)!/2 
    let bannery = bheight/2 - (image?.size.height)!/2 

    imageView.frame = CGRect(x: bannerx, y: bannery, width: bwidth, height: bheight) 
    imageView.contentMode = .scaleAspectFit 
    navigationItem.titleView = imageView 
} 
+0

究竟哪一行導致錯誤? – rmaddy

回答

0

當你沒有必要一個合法的圖像您收到此錯誤信息添加到您的let image = UIImage(named: "2000")。它是nil。您的代碼在let bannerx = bwidth/2 - (image?.size.width)!/2上崩潰。確保您在該行之後繼續執行之前擁有正確的映像。

替換:

let image = UIImage(named: "2.png") 

有了:

guard let image = UIImage(named: "2") else { return } 

這樣做,你鴕鳥政策需要強制選擇使用下面的行,因此更換以下行的bannerxbannery與你:

let bannerx = bwidth/2 - (image.size.width)/2 
let bannery = bheight/2 - (image.size.height)/2