UIControl,相信大家對其並不陌生吧,比如平常最常用的UIButton就是繼承自UIControl的。按照慣例,還是先來看看為什麼有UIControl這個類?什麼時候用到它? 查下文檔就可以看到其是繼承自UIView的,而對於其用途,官方對其有這麼一段描述: To observe or modify the dispatch of action messages to targets for particular eventsTo do this, override sendAction:to:forEvent:, evaluate the passed-in selector, target object, or UIControlEvents bit mask, and proceed as required. To provide custom tracking behavior (for example, to change the highlight appearance)To do this, override one or all of the following methods: beginTrackingWithTouch:withEvent:, continueTrackingWithTouch:withEvent:,endTrackingWithTouch:withEvent:.簡要點說,就是當你需要自訂一個類似於button的控制項,也可自訂響應事件。而要這些,你必須實現相應的方法。詳情可看下官方文檔。 簡要挑幾個比較常用有代表性的屬性和方法: contentHorizontalAlignment:這個屬性主要是用於設定你自訂的這個空間裡面的text or image在水平方向上的位置,而同樣的另一個對應屬性contentVerticalAlignment則用於設定垂直方向上的位置屬性,取值可如下: typedef enum { UIControlContentHorizontalAlignmentCenter = 0, UIControlContentHorizontalAlignmentLeft = 1, UIControlContentHorizontalAlignmentRight = 2, UIControlContentHorizontalAlignmentFill = 3,} UIControlContentHorizontalAlignment;typedef enum { UIControlContentVerticalAlignmentCenter = 0, UIControlContentVerticalAlignmentTop = 1, UIControlContentVerticalAlignmentBottom = 2, UIControlContentVerticalAlignmentFill = 3,} UIControlContentVerticalAlignment;state selected highlighted這幾個從字面上就能看出其作用,而對於其相應的state,ios對其有以下定義:enum { UIControlStateNormal = 0, UIControlStateHighlighted = 1 << 0, UIControlStateDisabled = 1 << 1, UIControlStateSelected = 1 << 2, UIControlStateApplication = 0x00FF0000, UIControlStateReserved = 0xFF000000}; 看完了上面幾個屬性,再來看下一個最常用的方法:- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents target:目標,通常取值self action:一個sel值,用於定義一個方法,然後當你點擊後面的controlEvents相應事件時開始執行。eg.@selector(myMethod:) controlEvents:事件,詳情看上面的state定義。 不宜太長,就寫這麼多先,主要用到的就這麼幾個,但就是很常用,最近項目經常會寫這類的自訂控制項。