1. 程式人生 > >iOS知識小集 第三期

iOS知識小集 第三期

這一期主要有三個內容:

  1. Tint Color
  2. Build Configurations in Swift
  3. 鍵盤事件

Tint Color

iOS 7後,UIView新增加了一個tintColor屬性,這個屬性定義了一個非預設的著色顏色值,其值的設定會影響到以檢視為根檢視的整個檢視層次結構。它主要是應用到諸如app圖示、導航欄、按鈕等一些控制元件上,以獲取一些有意思的視覺效果。

tintColor屬性的宣告如下:

1
var tintColor: UIColor!

預設情況下,一個檢視的tintColor

是為nil的,這意味著檢視將使用父檢視的tint color值。當我們指定了一個檢視的tintColor後,這個色值會自動傳播到檢視層次結構(以當前檢視為根檢視)中所有的子檢視上。如果系統在檢視層次結構中沒有找到一個非預設的tintColor值,則會使用系統定義的顏色值(藍色,RGB值為[0,0.478431,1],我們可以在IB中看到這個顏色)。因此,這個值總是會返回一個顏色值,即我們沒有指定它。

tintColor屬性相關的還有個tintAdjustmentMode屬性,它是一個列舉值,定義了tint color的調整模式。其宣告如下:

1
var
tintAdjustmentMode: UIViewTintAdjustmentMode

列舉UIViewTintAdjustmentMode的定義如下:

1
2
3
4
5
enum UIViewTintAdjustmentMode : Int {
    case Automatic          // 檢視的著色調整模式與父檢視一致
    case Normal             // 檢視的tintColor屬性返回完全未修改的檢視著色顏色
    case Dimmed             // 檢視的tintColor屬性返回一個去飽和度的、變暗的檢視著色顏色
}

因此,當tintAdjustmentMode屬性設定為Dimmed時,tintColor的顏色值會自動變暗。而如果我們在檢視層次結構中沒有找到預設值,則該值預設是Normal

tintColor相關的還有一個tintColorDidChange方法,其宣告如下:

1
func tintColorDidChange()

這個方法會在檢視的tintColortintAdjustmentMode屬性改變時自動呼叫。另外,如果當前檢視的父檢視的tintColortintAdjustmentMode屬性改變時,也會呼叫這個方法。我們可以在這個方法中根據需要去重新整理我們的檢視。

示例

接下來我們通過示例來看看tintColor的強大功能(示例盜用了Sam Davies寫的一個例子,具體可以檢視iOS7 Day-by-Day :: Day 6 :: Tint Color,我就負責搬磚,用swift實現了一下,程式碼可以在這裡下載)。

先來看看最終效果吧(以下都是盜圖,請見諒,太懶了):

image

這個介面包含的元素主要有UIButtonUISliderUIProgressViewUIStepperUIImageViewToolBar和一個自定義的子檢視CustomView。接下來我們便來看看修改檢視的tintColor會對這些控制元件產生什麼樣的影響。

ViewControllerviewDidLoad方法中,我們做了如下設定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
override func viewDidLoad() {
  super.viewDidLoad()
    println("\(self.view.tintAdjustmentMode.rawValue)")         // 輸出:1
    println("\(self.view.tintColor)")                           // 輸出:UIDeviceRGBColorSpace 0 0.478431 1 1
    self.view.tintAdjustmentMode = .Normal
    self.dimTintSwitch?.on = false
    // 載入圖片
    var shinobiHead = UIImage(named: "shinobihead")
    // 設定渲染模式
    shinobiHead = shinobiHead?.imageWithRenderingMode(.AlwaysTemplate)
    self.tintedImageView?.image = shinobiHead
    self.tintedImageView?.contentMode = .ScaleAspectFit
}

首先,我們嘗試列印預設的tintColortintAdjustmentMode,分別輸出了[UIDeviceRGBColorSpace 0 0.478431 1 1]1,這是在我們沒有對整個檢視層次結構設定任何tint color相關的值的情況下的輸出。可以看到,雖然我們沒有設定tintColor,但它仍然返回了系統的預設值;而tintAdjustmentMode則預設返回Normal的原始值。

接下來,我們顯式設定tintAdjustmentMode的值為Normal,同時設定UIImageView的圖片及渲染模式。

當我們點選”Change Color“按鈕時,會執行以下的事件處理方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
@IBAc