如何在Swift中更改UIButton图像

发布于 2021-01-31 23:47:40

我正在尝试使用Swift更改UIButton的图像…我该怎么办

这是OBJ-C代码。但是我不知道Swift:

[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
关注者
0
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    从您的Obc-C代码中,我认为您想为按钮设置图片,因此请尝试以下方式:

    let playButton  = UIButton(type: .Custom)
    if let image = UIImage(named: "play.png") {
        playButton.setImage(image, forState: .Normal)
    }
    

    简而言之:

    playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
    

    对于Swift 3:

    let playButton  = UIButton(type: .custom)
    playButton.setImage(UIImage(named: "play.png"), for: .normal)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看