iOS 自定义控件




分为两个层面来处理


1.UI


2.Event




1.关于UI部分,分为Appearance,Animation

1.1 Appearance是UI界面的构成部分,开发之前需要构思自定义控件的组成元素,可以使用UIView及其子类,CALayer及其子类,还有使用图片替代,或者是使用CoreGraphics描绘

在这需要注意使用:

layoutSubviews方法中定义组成元素的frame信息 //调用组件的layoutIfNeed方法,会调用此方法,而setNeedsLayout不会立即调用此方法,只是将组件标记为需要重新布局如果要立即刷新,要先调用[view setNeedsLayout],把标记设为需要布局,然后马上调用[view layoutIfNeeded],实现布局
在视图第一次显示之前,标记总是“需要刷新”的,可以直接调用[view layoutIfNeeded]

layoutSubviews在以下情况下会被调用:
a.init初始化不会触发,但是是用initWithFrame 进行初始化时,当rect的值不为CGRectZero时,也会触发
b.addSubview会触发
c.设置view的Frame会触发,当然前提是frame的值设置前后发生了变化
d.滚动一个UIScrollView会触发
e.旋转Screen会触发父UIView上的此方法
f.改变一个UIView大小的时候也会触发父UIView上的此方法

drawRect:方法中使用Core Graphics框架进行渲染 //调用组件的setNeedsDisplay方法,或者是setNeedsDisplayInRect:方法(参数不能是0),会调用此方法

sizeThatFits:方法是返回最终控件组件的size信息   //调用组件的sizeToFit,会调用此方法

以上方法的优先级sizeThatFits:>layoutSubviews>drawRect:


1.2 Animation 是控件的动画效果部分,使用Core Animation框架或者是组成部分自带的动画效果都是可以的


2.关于Event部分,iOS的系统中支持的Event类型是Touch,Motion,Press,Remote-Control

每一类型的事件都有delegate方法去处理,在设计自定义控件的时候,想好控件组件需要处理的事件类型

接下来要说的是,在设计控件组件的时候,需要选择继承的父类,UIKit框架中的继承关系如下图:

ios 组件化控件 组件 iphone_UI

1.选择继承UIResponder,需要实现上面提到的事件处理的方法,例如Touch事件:The primary event-handling methods for touches are touchesBegan:withEvent:touchesMoved:withEvent:touchesEnded:withEvent:, and touchesCancelled:withEvent:.

在这需要注意使用:


 - canPerformAction:withSender:


Requests the receiving responder to enable or disable the specified command in the user interface.


   - targetForAction:withSender:


Returns the target object that responds to an action.


userActivity


An object encapsulating a user activity supported by this responder.







2.选择继承UIControl及其子类,此类使用了 Target-Action机制,很方便为控件组件添加 UIControlEventsWhen adding an action method to a control, you specify both the action method and an object that defines that method to the addTarget:action:forControlEvents:method

在这需要注意使用:

  • Override the sendAction:to:forEvent: method of an existing subclass to observe or modify the dispatching of action methods to the control’s associated targets. You might use this method to modify the dispatch behavior based on the specified object, selector, or event.(这个方法可以监控或者修改控件组件使用addTarget:action:forControlEvents:绑定的方法)

- sendActionsForControlEvents:


Calls the action methods associated with the specified events.(这个方法的调用将会执行addTarget:action:forControlEvents:绑定的方法)