やること
- Extensionファイルを追加
- 拡張メソッド追加
Extensionファイル
既存クラスの前に extension と付けて好きなメソッドを書くだけです。
今回は指定のUIColorを返すメソッドと、
0xFFFFFF のような数値からUIColorを返すメソッドを追加しました。
※UIColorを使うには UIKit をimportしておく必要があります。
Extension
import UIKit
import Foundation
extension UIColor {
// Twitterの水色を返します
class func twitterColor()->UIColor{
return UIColor.rgbColor(0x00ACED)
}
// Facebookの青色を返します
class func facebookColor()->UIColor{
return UIColor.rgbColor(0x305097)
}
// Lineの緑色を返します
class func lineColor()->UIColor{
return UIColor.rgbColor(0x5AE628)
}
// UIntからUIColorを返します #FFFFFFのように色を指定できるようになります
class func rgbColor(rgbValue: UInt) -> UIColor{
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat( rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
利用例
tableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let colors: [(color: UIColor, text: String)] = [
(UIColor.twitterColor(), "twitterColor"),
(UIColor.lineColor(), "lineColor"),
(UIColor.facebookColor(), "facebookColor"),
(UIColor.rgbColor(0xFF0000),"rgbColorSample 0xFF0000")
]
cell.textLabel?.text = colors[indexPath.row].text
cell.backgroundColor = colors[indexPath.row].color
if (cell.backgroundColor == UIColor.blackColor())
{
cell.textLabel?.textColor = UIColor.whiteColor()
}
return cell
}
実装結果
ブランドカラーなどデフォルト以外のUIColorを様々な箇所で使う際に便利です。
Extensionファイルとは別のファイルからもメソッドを自由に呼び出せます。
参考サイト
以下のサイトを参考にしました。
Swiftサラリーマンさん
Extensionとは?
http://swift-salaryman.com/extension.php
UIColorを16進数から取得
http://swift-salaryman.com/uicolorutil.php
akiyumoさん
【備忘録】主要SNSブランドカラーの値 一覧
http://akiyum.com/webdesign_tips/sns-brandcolor.html
参考ソース