zoukankan      html  css  js  c++  java
  • 自定义视图

    自定义视图的出现,是为了把众多的view放在一个view里,创建的时候,只要创建这个view就好。这样能用尽量少的代码,进行更多更快的布局。

    自定义视图,遵循以下几个步骤:

    1、创建一个类,继承于UIView,重新定义初始化方法,

    - (instancetype)initWithFrame:(CGRect)frame

    这个方法里,[ self setupView ]调用一个我们自定义的私有方法,来实现几个UILabel+UITextField等组合的布局。

    2、在appdelegate中创建这个用于布局的类。

    LTView.h

    声明两个属性分别为UILabel和UITextField类型的属性

    #import <UIKit/UIKit.h>

     

    @interface LTView3 : UIView

     

    @property(nonatomic,retain)UILabel *aLabel;

    @property(nonatomic,retain)UITextField *aTextField;

     

    @end

    LTView.m

    重写初始化方法,在初始化方法内,对两个属性进行初始化,完成内部的布局

    #import "LTView.h"

     

    @implementation LTView

     

    - (instancetype)initWithFrame:(CGRect)frame{

        self = [super initWithFrame:frame];

        if (self) {

           

            [self p_setupView];

    }

        return self;

    }

    //  私有方法

    // 把初始化方法中的视图布局搬到私有方法中

    - (void)p_setupView{

        self.aLabel = [[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, CGRectGetHeight(self.frame))] autorelease];

        self.aLabel.backgroundColor = [UIColor cyanColor];

        [self addSubview:_aLabel];

       

        self.aTextField = [[[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.aLabel.frame)+20, CGRectGetMinY(self.aLabel.frame),CGRectGetWidth(self.frame)- CGRectGetWidth(self.aLabel.frame)-20 , CGRectGetHeight(self.aLabel.frame))] autorelease];

        self.aTextField.backgroundColor = [UIColor yellowColor];

        [self addSubview:_aTextField];

    }

    - (void)dealloc{

        [self.aTextField release];

        [self.aLabel release];

        [super dealloc];

    }

    @end

     

    AppDelegate.m

    这样创建一个UILabel和一个UITextField这两个视图的布局,只需要创建一个LTView类的对象即可。

     // 创建LTView

        LTView *ltv1 = [[LTView alloc]initWithFrame:CGRectMake(50, 50, 300, 50)];

        ltv1.backgroundColor = [UIColor blueColor];

        [self.window addSubview:ltv1];  

        // 释放

        [ltv1 release];

        ltv1 = nil;

     

  • 相关阅读:
    Tomcat部署项目
    正则表达式
    文件的上传和下载
    实现扫码登陆
    onepill Android端
    部署SpringBoot到阿里云
    Gson
    HTML自动刷新页面
    Spring Data JPA根据属性名查询
    Spring Date JPA实现增删改查
  • 原文地址:https://www.cnblogs.com/Coder-GT/p/4866361.html
Copyright © 2011-2022 走看看