Ios 设置按钮的图像

Ios 设置按钮的图像,ios,uibutton,uicollectionview,uicollectionviewcell,Ios,Uibutton,Uicollectionview,Uicollectionviewcell,我遇到了一个我无法解决的问题 我有一个结构,希望更改每个集合视图中按钮的图像。我的文字/图像按照计划工作。然而,当尝试更改图像按钮时,我感到很困难。谁能帮帮我吗 class CollectionViewContent{ var caption = "" var mainImage: UIImage! var userProfileImage : UIButton init(caption: String, mainImage: UIImage!, userP

我遇到了一个我无法解决的问题

我有一个结构,希望更改每个集合视图中按钮的图像。我的文字/图像按照计划工作。然而,当尝试更改图像按钮时,我感到很困难。谁能帮帮我吗

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
而不是:

postedUserProfileImage = posts.postedUserProfileImage
你应该做:

postedUserProfileImage.setImage(posts.postedUserProfileImage.image(for: UIControlState.normal), for: UIControlState.normal)
由于postedUserProfileImage是一个UIButton,因此需要使用setImage方法为特定于控件的控件状态设置其映像。如果没有为其他控制状态设置图像,则正常状态的图像也将用于其他控制状态


由于posts.postedUserProfileImage也是一个UIButton,如下面的注释所述,您需要通过imagefor:方法获取按钮的图像。

好的,我明白了。如何设置图像?感谢您的快速回复:请参阅上面的代码:它告诉您如何设置图像。除非您在说设置图像时是指其他内容?我明白了,我添加了一行代码,出现了一个错误,无法将类型为“UIButton”的值转换为预期的参数类型“UImage”。我基本上希望有一个按钮,但在每个集合视图中,按钮的图像都会更改为我选择的图像:啊,因为你发布的代码没有指定posts.postedUserProfileImage的类型,所以我认为它是UIImage。如果它是一个按钮,而您只是试图将一个按钮的图像设置为另一个按钮,那么请参阅上面我修改的代码。