簡體   English   中英

UIImage 不顯示使用 Swift

[英]UIImage not displaying using Swift

用 Swift 編寫的用於顯示 UIImages 的代碼可以在 iOS 8.0 模擬器中運行,但由於某種原因不能在運行 IOS 7.0 的手機上運行。

let image1 = UIImage(named: "img1")
let imageview = UIImageView(image: image1)
self.view.addSubview(imageview)

let image2 = UIImage(named: "img2")
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: image2.size)
button.setImage(image2, forState: UIControlState.Normal)
self.view.addSubview(button)

圖像位於正確的位置,具有正確的大小和有效的引用,它們只是沒有顯示,除非在運行 iOS 8 的模擬器上。

這是其他人的問題嗎?

編輯:從 Images.xcassets 中刪除,清理項目並將文件復制到包本身似乎對我有用。

為了顯示圖像,您必須按以下方式更改代碼

let image1 = UIImage(named: "img1.jpg")
let imageview = UIImageView(image: image1)
self.view.addSubview(imageview)

let image2 = UIImage(named: "img2.jpg")
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: image2.size)
button.setImage(image2, forState: UIControlState.Normal)
self.view.addSubview(button)

記住 swift 不支持 .png 格式的圖像,它支持 .jpg 格式。

我在 iOS 8-Simulator 和我的 iOS 7 設備上嘗試了你的代碼,它做了它應該做的。 所以不,就我而言,我認為沒有問題。

我將 img1 更改為 img1.JPG(文件名),將 img2 更改為 img2.png。 我將圖像直接復制到視圖控制器所在的文件夾中。

問題的投票與其他答案之間似乎存在脫節,因此我將添加一個關於如何在 Swift 中顯示圖像的通用答案。 無論如何,這就是最初將我帶到這里的原因。

如何在 Swift 中顯示圖像

使用UIImage獲取對主包中圖像的引用。

let image = UIImage(named: "rocket.png")
imageView.image = image

筆記

  • imageView是一個UIImageView
  • 在我的測試中,包含或排除 .png 文件擴展名並沒有產生什么不同。 但是,如果您使用多種圖像格式,則可能需要包括在內。
  • 同樣在我的測試中,圖像是直接添加到項目中還是在 Assets.xcassets 中都沒有區別。
  • 如果您需要不在主包中的圖像,請參閱此問題
  • 根據此處原始問題中的編輯,刪除圖像並將其重新添加到包中是解決問題的方法。

您將檢查圖像是否已添加到您的框架中,如果未選中,您將無法加載資源,但如果您選中它,圖像將被加載在此處輸入圖片說明

我將我的圖像存儲在“Images.xcassets”文件夾中,我的圖像沒有出現在我的設備上,但它們確實出現在了模擬器上。 為了在我的設備(iPhone 5)上顯示“Images.xcassets”圖像,對我有用的解決方案是復制“Images.xcassets”文件夾的捆綁資源

復制捆綁資源:選擇目標>構建階段>復制捆綁資源>選擇“+”(添加項目)>選擇“Images.xcassets

斯威夫特 5:

由於各種原因,接受的答案不再編譯,所以這是我的更新版本:

    let image1 = UIImage(named: "img1.jpg")
    if let myImage1 = image1 {
        let imageview = UIImageView(image: myImage1)
        self.view.addSubview(imageview)
    } else {
        print ("img1 not loaded")
    }

    let image2 = UIImage(named: "img2.jpg")

    if let myImage2 = image2 {
        let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: myImage2.size))
        button.setImage(myImage2, for: .normal)
        self.view.addSubview(button)
    } else {
        print ("img2 not loaded")
    }

一種可能的原因是高度。 檢查 UIImageView 的高度,可能在代碼或故事板中更高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM