【问题标题】:Setting images of a button设置按钮的图像
【发布时间】:2017-09-03 12:35:07
【问题描述】:

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

我有一个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

【问题讨论】:

    标签: ios uibutton uicollectionview uicollectionviewcell


    【解决方案1】:

    代替:

    postedUserProfileImage = posts.postedUserProfileImage
    

    你应该这样做:

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

    由于postedUserProfileImageUIButton,因此您需要使用setImage 方法来设置它的图像以用于特定于控件的控件状态。如果没有为其他控制状态设置图像,则正常状态的图像也用于其他控制状态。

    由于posts.postedUserProfileImage 也是UIButton(如下面的cmets 所述),您需要通过image(for:) 方法获取按钮的图像。

    【讨论】:

    • 好的,我明白了。我将如何设置图像?感谢您的快速回复:)
    • 查看我上面的代码 :) 它告诉你如何设置图像。除非您说“设置图像”时的意思是别的?
    • 我明白了,我已经添加了这行代码,但出现错误“无法将 'UIButton' 类型的值转换为预期的参数类型 'UImage?'”。我基本上希望有一个按钮,但是在每个集合视图中,按钮的图像都会更改为我选择的任何图像。 :)
    • 啊,因为您发布的代码没有指定posts.postedUserProfileImage 的类型,我以为是UIImage。如果它是一个按钮,而您只是想将一个按钮的图像设置为另一个按钮,那么请查看我上面修改过的代码。
    猜你喜欢
    • 2020-03-19
    • 2013-09-27
    • 2011-02-15
    • 2014-03-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多