iOS中Tager-Action 应用举例实现 高内聚低耦合

来源:互联网 发布:西门子300plc编程软件 编辑:程序博客网 时间:2024/05/22 04:41

iOS中Tager-Action 应用举例实现 高内聚低耦合

  • 文章主要实现的是UILabel可以根据实际要求而改变

  • 首先创建根视图控制器rootViewController 继承与UIViewController

  • 再创建ActionView继承与UIView
  • 在ActionView.h文件中写实例变量自定义初始化方法
@interface ActionView : UIView{    id  _target;    SEL _action;}- (id)initWithTarget:(id)aTarget action:(SEL)aAction;@end
  • 在ActionView.m文件中实现方法
- (id)initWithTarget:(id)aTarget action:(SEL)aAction{    self = [super init];    if (self) {        _action = aAction;        _target = aTarget;    }    return self;}
  • 在ActionView.m中 实现触摸屏幕中的label时 触发的事件
// 点击时- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [_target performSelector:_action withObject:self];}//移动时 label跟随触点移动- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{    UITouch *touth = [touches anyObject];    CGPoint point1 = [touth locationInView:self.window];    CGPoint point2 = [touth previousLocationInView:self.window];    CGFloat x = self.center.x - point2.x;    CGFloat y = self.center.y - point2.y;    CGPoint newCenter = CGPointMake(point1.x + x, point1.y + y);    self.center = newCenter;}
  • 然后 在rootViewController.m文件中的viewDidLoad里 编写代码
 - (void)viewDidLoad {    [super viewDidLoad];    // 点击时改变颜色    ActionView *actionView1 = [[ActionView alloc]initWithTarget:self action:@selector(changeColor:)];    actionView1.frame = CGRectMake(50, 50, 100, 100);    actionView1.backgroundColor = [UIColor yellowColor];    [self.view addSubview:actionView1];    [actionView1 release];    //点击时改变大小    ActionView *actionView2 = [[ActionView alloc]initWithTarget:self action:@selector(changeFrame:)];    actionView2.frame = CGRectMake(100, 100, 100, 100);    actionView2.backgroundColor = [UIColor blackColor];    [self.view addSubview:actionView2];    [actionView2 release];}
  • 同样在rootViewController.m文件中写入对应方法的函数
// 改变大小随机大小- (void)changeFrame:(UIView *)aView{    aView.bounds = CGRectMake(0, 0, arc4random()%320/1.0, arc4random()%480/1.0);}// 改变颜色随机色- (void)changeColor:(UIView *)aView{    aView.backgroundColor = [UIColor colorWithRed:arc4random()%10/9.0 green:arc4random()%10/9.0 blue:arc4random()%10/9.0 alpha:1.0];}
0 0