iOS开发中使用链式编程创建UIButton

2017-05-02  本文已影响0人  米米0311

具体的代码参见 https://github.com/yanjie311/Chain-coding---primary

链式编程

对于有一定开发经验的人来说链式编程并不陌生,有很多知名的开源库都是采用的这种编程方式,在iOS库中,Masory和Snapkit也是典型的使用链式编程的例子。
大体来说,链式编程就是将多个操作(多行代码)通过某种操作符(通常是点号.)链接成一句的代码.便代码更加紧凑,可读性也更好,降低了代码的重复度.比如以下代码:

//普通方法实现
    [sender setImage:[UIImage imageNamed:@"newcreate_click.png"] forState:UIControlStateNormal];
    sender.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [sender setTitle:@"你好" forState:UIControlStateNormal];
    [sender setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    sender.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:sender];
    //链式结构实现
    sender1.ImagePrams(@"newcreate_click.png",1)
    .TitlePrams(@"你好", 17, [UIColor grayColor], 1)
    .ClickAction(sender1);
    [self.view addSubview:sender1];

通过这个例子读者应该可以更清楚的了解什么是链式编程风格.简单来说,链式编程风格要有以下特点:

链式编程的利弊

使用链式编程最主要的好处是可以使代码更简洁,写起来一种"爽快"感.设计优秀的链式编程可以大大降低重复的代码,增强逻辑感.不足之处就是对开
发者的业务逻辑能力要求较高,同时因为链式编程都是调用函数,所以有可能会造成过深的函数调用栈.稍微影响性能.

创建按钮

 WYJLinkerButton* sender1 = [WYJLinkerButton creatButton:CGRectMake(100, 100, 100, 100)];
    sender1.ImageEdgInsets(20,0,60,60)
    .TitleEdgInsets(0,63,100,23)
    .ImagePrams(@"newcreate_click.png",1)
    .TitlePrams(@"你好", 17, [UIColor grayColor], 1)
    .ClickAction(sender1);
    [self.view addSubview:sender1];

    WYJLinkerButton* sender2 = [WYJLinkerButton creatButton:CGRectMake(100, 200, 100, 100)];
    sender2.backgroundColor = [UIColor blueColor];    sender2.ImageEdgInsets(0,25,40,40).TitleEdgInsets(45,32,55,25).ImagePrams(@"newcreate_click.png",1).TitlePrams(@"不开心!",16,[UIColor redColor], 1).ClickAction(sender2);
    sender2.jmImagev.layer.cornerRadius = 10;
    sender2.jmImagev.layer.masksToBounds = YES;
    [self.view addSubview:sender2];

    WYJLinkerButton* sender3 = [WYJLinkerButton creatButton:CGRectMake(120, 300, 80, 30)];
    sender3.ImageEdgInsets(0,2.5,25,25)
    .TitleEdgInsets(27,2.5,55,25)
    .ImagePrams(@"newcreate_click.png",1)
    .TitlePrams(@"发微博",16,[UIColor blueColor], 1)
    .ClickAction(sender3);
    [self.view addSubview:sender3];

简单举例(给按钮添加label)

** Title的参数值,“(title, fountSize, textColor)” */
@property(nonatomic,copy)
WYJLinkerButton* (^TitlePrams)(NSString* title,NSInteger fountSize,UIColor*textColor, NSTextAlignment textAlignment);
- (WYJLinkerButton *(^)(NSString *, NSInteger, UIColor *, NSTextAlignment))TitlePrams {
    return ^WYJLinkerButton* (NSString* title,NSInteger fountSize,UIColor*textColor, NSTextAlignment textAlignment){
        self.jmLabel.text = title;
        self.jmLabel.textColor = textColor;
        self.jmLabel.font = [UIFont systemFontOfSize:fountSize];
        self.jmLabel.textAlignment = textAlignment;
        return self;
    };
}

github上有具体的代码参考,欢迎大家批评指正,谢谢

上一篇下一篇

猜你喜欢

热点阅读