1. 程式人生 > >swift UITabBarItem修改字型顏色和圖示顏色

swift UITabBarItem修改字型顏色和圖示顏色

 storyboard建立的選項卡,圖片顏色固定,字型顏色固定。可以說完全沒法用,查閱了好久的api和資料才找到修改的辦法。

將UITabBarItem連線到FirstViewController

程式碼如下:

//
//  FirstViewController.swift
//  demo
//
//  Created by sunger on 15/3/24.
//  Copyright (c) 2015年 sunger. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var tab1: UITabBarItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //這裡修改圖片顏色,使得圖片和原圖顏色一致
        tab1.image=UIImage(named: "tab1")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
        //這裡修改字型顏色
        var attributes =  [NSForegroundColorAttributeName: UIColor(red: 220.0/255.0, green: 104.0/255.0, blue: 1.0/255.0, alpha: 1.0),
            NSFontAttributeName: UIFont(name: "Heiti SC", size: 24.0)!]
        tab1.setTitleTextAttributes(attributes , forState: UIControlState.Selected)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

主要參考官方api和如下幾篇文章;

2.修改字型顏色

http://www.cnblogs.com/xgbzsc/archive/2013/01/16/2862611.html

http://blog.csdn.net/willyang519/article/details/38855719

http://stackoverflow.com/questions/7810563/how-do-you-use-settitletextattributesforstate-in-uibaritem

最後實現如下效果