2017-04-08 97 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