LoginSignup
7
7

More than 5 years have passed since last update.

あのTabBarの背景色を僕達はまだ知らない。

Last updated at Posted at 2016-02-04

やること

UITabBarの選択されているところだけ、背景をブラックにしたい。
5sの横幅とアイテム数をもとに作った画像を背景に設定していたが
iPhoen6やPlusのサイズだと、設定していた画像がはみ出してしまった。

なのでコードでUIImageを作って、当てはめることにしました。

実装

TabBarController.swift
override func viewDidLoad() {
    super.viewDidLoad()
    self.delegate = self
    self.tabBar.selectionIndicatorImage = setImage()
}

// 横幅とアイテム数をもとにUIImageを生成
func setImage() -> UIImage {   
     let size = CGSize(width: UIScreen.mainScreen().bounds.size.width/CGFloat((self.tabBar.items?.count)!), height: 49)
     UIGraphicsBeginImageContext(size)
     let cgContextRef = UIGraphicsGetCurrentContext()
     CGContextSetFillColorWithColor(cgContextRef, UIColor.blackColor().CGColor)
     CGContextSetAlpha(cgContextRef, 1.0)
     CGContextFillRect(cgContextRef, CGRectMake(0, 0, size.width, size.height))
     let colorImage = UIGraphicsGetImageFromCurrentImageContext()
     UIGraphicsEndImageContext()

     return colorImage
}

これで、選択した時の背景画像に幅が均等になったものがセットされます。
わざわざパターン別に画像を用意しなくても対応できる!
あと色は、お好みで!

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