9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIButtonをタップして画像を切り替える

Posted at

Todoリストなどを作成するとき、チェックマークのUIButtonをタップしてボタンの画像を切り替えたい時があると思います。実際に実装して注意点があったので書き残しておきます。

すぐ思いつく実装

自分は最初に以下のように実装しました。あまりにシンプルですね。

ViewController.swift
class ViewController: UIViewController {
    @IBOutlet weak var imageButton: UIButton!

    @IBAction func imageButtonPush(_ sender: Any) {
        
        let image = UIImage(named: "icon")
        imageButton.imageView?.image = image
    }
}

しかし、実際にボタンをタップしてみたところ画像は元のままで見た目が変更されませんでした。
UIImageViewから差し替える必要があるのでは?と思い、以下に変更して再度実行してみました。

ViewController.swift
class ViewController: UIViewController {
    @IBOutlet weak var imageButton: UIButton!

    @IBAction func imageButtonPush(_ sender: Any) {
        
        let image = UIImage(named: "icon")
        let imageView = UIImageView(image: image)
        imageButton.imageView? = imageView
    }
}

しかし、これでも画像がUIButtonに反映されませんでした。
そこでUIButtonをもう少し見てみると、 setImageメソッドを発見!こちらを試してみました。

ViewController.swift
class ViewController: UIViewController {
    @IBOutlet weak var imageButton: UIButton!

    @IBAction func imageButtonPush(_ sender: Any) {
        
        let image = UIImage(named: "icon")
        let state = UIControl.State.normal
        
        imageButton.setImage(image, for: state)
        
    }
}

上記実装でボタンを押下したところ、無事画像が切り替わりました。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?