我遇到了一个我无法解决的问题。
我有一个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
答案 0 :(得分:1)
而不是:
postedUserProfileImage = posts.postedUserProfileImage
你应该这样做:
postedUserProfileImage.setImage(posts.postedUserProfileImage.image(for: UIControlState.normal), for: UIControlState.normal)
由于postedUserProfileImage
是UIButton
,您需要使用setImage
方法为控件特定控件状态设置其图像。如果没有为其他控制状态设置图像,则正常状态的图像也用于其他图像。
由于posts.postedUserProfileImage
也是UIButton
(如下面的评论所述),您需要通过image(for:)
方法获取按钮的图片。