0
1

More than 3 years have passed since last update.

UIToolBarについて、中のボタンタップ時におけるハイライトが不自然にならないように上部の枠線を消す

Posted at

非常にニッチだが、割と時間がかかったためメモしておく

やりたいこと

以下のUIToolBarを作る

  • ボタンに CustomView でボタンを利用し、ボタンのハイライトをONにする
  • 背景に独自画像を設定する
  • 上部の枠線は表示したくない

以下がベースのコード
ここで指定しているproduct_color.pngは1x1サイズの単色画像である

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // イメージカラーの画像を読み込む
        let productColorImage = UIImage(named: "product_color.png")!

        // UIViewController の背景をイメージカラーの画像に設定
        self.view.backgroundColor = UIColor(patternImage: productColorImage)

        // ツールバーの作成
        let toolBar = UIToolbar()

        // ツールバーのボタン間のスペース部品
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)

        // ツールバーのボタン1
        let button1 = UIButton()
        button1.setTitle("ボタン1", for: .normal)
        button1.showsTouchWhenHighlighted = true  // タップ時のハイライトを有効にする
        let buttonItem1 = UIBarButtonItem(customView: button1)

        // ツールバーのボタン2
        let button2 = UIButton()
        button2.setTitle("ボタン2", for: .normal)
        button2.showsTouchWhenHighlighted = true  // タップ時のハイライトを有効にする
        let buttonItem2 = UIBarButtonItem(customView: button2)

        // ボタンをツールバーに追加
        let buttonItems = [flexibleSpace, buttonItem1, flexibleSpace, buttonItem2, flexibleSpace]
        toolBar.setItems(buttonItems, animated: false)

        // ツールバーの前景の半透明を消す
        toolBar.isTranslucent = false

        // ツールバーの背景をイメージカラーの画像に設定
        toolBar.setBackgroundImage(productColorImage, forToolbarPosition: .any, barMetrics: .default)

        // TODO: ここで toolBar の上部の枠を消したい

        // ツールバーの部品を表示
        self.view.addSubview(toolBar)

        // ...略
    }
}

上記を実行すると、以下のような様子となる
01_初期状態.png

ボタンタップ時には、以下のようなハイライトが表示される
01_初期状態ボタンタップ.png

上記のハイライトを自然に見えるように維持しつつ、ツールバーの上部にグレーの枠線を消したい

方法

上手くいかなかった方法

clipsToBounds プロパティを true にすると、ハイライトがツールバーのサイズでクリップされてしまい、カッコ悪くなった

上手くいかなかった例
toolBar.clipsToBounds = true

以下のように、枠線は消えたが、
02_ClipsToBounds.png

ボタンタップ時のハイライトが、ツールバーの上部で切り取られてしまった。
02_ClipsToBoundsボタンタップ.png

上手くいった方法

ツールバーの shadowImage を設定する

上手くいった例
toolBar.setShadowImage(productColorImage, forToolbarPosition: .any)

上記の設定により、ハイライトも切り取られず、かつ枠線も消えた。
03_ShadowImageボタンタップ.png

参考

0
1
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
0
1