2017-04-08 92 views
0

我遇到了一個我無法解決的問題。設置按鈕的圖像

我有一個struct,並希望在每個集合視圖中更改按鈕的圖像。我的文字/圖片按照計劃運作。但是,當試圖更改圖像按鈕時,我正在掙扎。有人可以幫我嗎?

class CollectionViewContent{ 

    var caption = "" 
    var mainImage: UIImage! 
    var userProfileImage : UIButton 


    init(caption: String, mainImage: UIImage!, userProfileImage : UIButton!) 
    { 
     self.description = description 
     self.mainImage = featuredImage 
     self.userProfileImage = postedUserProfileImage 
    } 


    static func showPosts() -> [Posts] 
    { 
     return [ 
      Posts(description: "Sweet", mainImage: UIImage(named: "Image 1"), postedUserProfileImage:!), 
        Posts(description: "Awesome", mainImage: UIImage(named: "Image 2")!), 
        Posts(description: "WOW!", mainImage: UIImage(named: "Image 3")! 

       ) 
     ] 
    } 


} 

這是我collectionViewCell類

class colViewContetCollectionViewCell: UICollectionViewCell { 


    var posts: Posts! { 
     didSet { 
      updateUI() 

     } 
    } 
    @IBOutlet weak var featuredImage: UIImageView! 
    @IBOutlet weak var postCaptionLabel: UILabel! 
    @IBOutlet weak var postedUserProfileImage: UIButton! 



    func updateUI() { 
     postCaptionLabel?.text! = posts.title 
     featuredImage?.image! = posts.featuredImage 
     postedUserProfileImage = posts.postedUserProfileImage 
    } 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     self.layer.cornerRadius = 10.0 
     self.clipsToBounds = true 
    } 

} 

我覺得這行代碼是由不正確的方法,我也不太清楚。

postedUserProfileImage = posts.postedUserProfileImage 

回答

1

相反的:

postedUserProfileImage = posts.postedUserProfileImage 

你應該這樣做:

postedUserProfileImage.setImage(posts.postedUserProfileImage.image(for: UIControlState.normal), for: UIControlState.normal) 

由於postedUserProfileImageUIButton,你需要使用setImage方法來設置它的圖像可控制的具體控制州。如果沒有圖像被設置爲其他控制狀態,正常狀態的圖像也用於其他控制狀態。

而且由於posts.postedUserProfileImage也是UIButton(如下面的評論中所述),您需要通過image(for:)方法獲取按鈕的圖像。

+0

好的,我明白了。我將如何設置圖像?感謝您的迅速回復:) – TheNewbie

+0

看到我的代碼上面:)這告訴你如何設置圖像。除非你說「設置圖像」時你的意思是別的嗎? – Fahim

+0

我看到了,我添加了代碼行,並且出現錯誤「無法將類型'UIButton'的值轉換爲期望的參數類型'UImage?'」。我基本上希望有一個按鈕,但在每個集合視圖中,該按鈕的圖像將更改爲我選擇的任何圖像。 :) – TheNewbie