美文网首页
iOS 基础控件链式编程

iOS 基础控件链式编程

作者: 拾酥 | 来源:发表于2018-01-08 10:36 被阅读0次

    这方面的原理我就不说了,相关的文章还是很多的。写了一个常用的控件实现链式编程的一个小框架,算是在这方面的尝试吧。有兴趣的朋友可以试试~ GitHub连接

    先来看下效果图:


    demo.gif

    一般我们创建一个控件的方式:

      UILabel *test1 = [[UILabel alloc] init];
        test1.frame = CGRectMake(20, 50, 100, 30);
        test1.font = [UIFont systemFontOfSize:13];
        test1.text = @"古今多少事";
        test1.textColor = [UIColor whiteColor];
        test1.backgroundColor = [UIColor lightGrayColor];
        test1.textAlignment = NSTextAlignmentCenter;
        test1.layer.cornerRadius = 3.f;
        test1.layer.borderColor = [UIColor greenColor].CGColor;
        test1.layer.borderWidth = 1.f;
        [self.view addSubview:test1];
    

    现在,我们可以这样创建:

    UILabel *label = [[UILabel alloc] init];
        label.labelChain  // 取到labelChain
        .font([UIFont systemFontOfSize:13])
        .text(@"链式作死")
        .textColor([UIColor greenColor])
        .viewMaker()    // 调用到UIView的链
        .frame(CGRectMake(20, 100, 100, 40))
        .backgroundColor([UIColor whiteColor])
        .addToSuperView(self.view)
        .labelMaker()   // 可以再回调到label链
        .textAlignment(NSTextAlignmentCenter)
        .layerMaker()   // 调到layer链
        .cornerRadius(5)
        .borderColor([UIColor redColor].CGColor)
        .borderWidth(1.f); 
    

    这里,UILabel的链不能直接调用UIView链上的属性或方法,需要先调用到UIView的链上面,也就是.viewMaker(),同样的,其他子类也要调用父类的时候属性或方法的时候也需要这么做,同时,父类也可以再调用到子类的链上面,比如.labelMaker()

    要注意的一点,调用到CALayer的链.layerMaker()之后,不能再回调回来,所以,最好在最后调用Layer链。因为这个属性的特殊性,每个子类都能直接调用.layerMaker()

    目前支持的类有UIView,UILabel,UIScrollView,UITableView,UICollectionView,UICollectionViewFlowLayout,UIControl
    UIButton,UITextView,UITextField,UIImageView,还有CALayer

    作为UITextFieldUITextView最常用且比较容易忽略的UITextInputTraits协议中的方法,这里分别复制到了UITextFieldUITextView
    两个类中,以便使用。。。我在想UIControl中的方法要不要也复制到UIButtonUITextField中去。。。

    https://github.com/tengshuq/TableViewPlaceholder
    如果您觉得有帮助,GitHub上来个star吧~~

    相关文章

      网友评论

          本文标题:iOS 基础控件链式编程

          本文链接:https://www.haomeiwen.com/subject/dnwvnxtx.html