ios学习笔记之UIControl解读
UIControl,相信大家对其并不陌生吧,比如平常最常用的UIButton就是继承自UIControl的。按照惯例,还是先来看看为什么有UIControl这个类?什么时候用到它?
查下文档就可以看到其是继承自UIView的,而对于其用途,官方对其有这么一段描述:
-
To observe or modify the dispatch of action messages to targets for particular events
To do this, override
sendAction:to:forEvent:
, evaluate the passed-in selector, target object, orUIControlEvents
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定义。
不宜太长,就写这么多先,主要用到的就这么几个,但就是很常用,最近项目经常会写这类的自定义控件。