我們常需要客製 UITextField 的外觀。UITextField 提供了多個可覆寫的方法,每個都回傳一個 CGRect,用來指定各個部件的邊界範圍,甚至能修改 placeholder 的顏色與字體。
常見的有:textRectForBounds:(重置文字區域)、drawTextInRect:(改變繪製文字屬性)、placeholderRectForBounds:(重置佔位符區域)、drawPlaceholderInRect:(改變繪製佔位符屬性)、borderRectForBounds:(重置邊緣區域)、editingRectForBounds:(重置編輯區域)、clearButtonRectForBounds:(重置清除鈕位置,但改變 size 可能導致圖示失真),以及 leftViewRectForBounds:、rightViewRectForBounds: 等。覆寫時若呼叫 super 可保留預設繪製,若要完全自繪則不需呼叫 super。
建立一個繼承自 UITextField 的 CustomTextField,覆寫以下方法:
· clearButtonRectForBounds::調整清除鈕位置。
· placeholderRectForBounds::控制佔位符位置,例如左右縮排。
· textRectForBounds::控制顯示文字的位置。
· editingRectForBounds::控制編輯時文字的位置。
· leftViewRectForBounds::控制左側視圖的位置。
· drawPlaceholderInRect::這是改變 placeholder 顏色與字體的關鍵。可先用 [[UIColor orangeColor] setFill] 設定填色,再用 [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:20]] 以指定字體繪製。
在 viewDidLoad 等方法中建立 CustomTextField 實例,設定 placeholder、邊框樣式、文字對齊、delegate、清除鈕模式與預設文字,並可透過 leftView 與 leftViewMode 加上自訂圖示,最後 addSubview 加入畫面即可。