免费开源的iOS开发学习平台

UIView详解:9-使用代码创建自定义UIView

在开发过程中,经常需要根据需求去定制各种式样的UIView对象。当需要定制UIView类时,可以使用纯代码以及Xib两种方式,在实现方法上稍有区别,但是有些共同的注意点必须特别关注,最好按照苹果建议的步骤和要求来创建自定义UIView。

使用代码创建自定义View的步骤

当使用代码创建自定义UIView时,可以按照如下步骤进行:

  • 新增自定义View类,继承自UIView类,Xcode自动生成.h/.m文件;
  • 在.m文件中,实现initWithFrame:方法。在该方法中,对视图的属性进行设置,并创建、添加子视图;
- (instancetype)initWithFrame:(CGRect)frame
{
    NSLog(@"%s",__func__);
    self = [super initWithFrame:frame];
    if (self) {
        //定制View
        self.backgroundColor = [UIColor blueColor];
        self.alpha = 0.5;     
        self.userInteractionEnabled = YES; //设置为NO后,不再响应touch方法
        self.multipleTouchEnabled = YES;    
        //控制子视图不能超出父视图的范围
        self.clipsToBounds = YES;      
        //添加子视图
        [self subView];       
        //添加手势
        UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longpressAction)];
        [self addGestureRecognizer:longpress];        
    }
    return self;
}
  • 添加子视图属性,并进行懒加载
@interface MYView()
@property (nonatomic, strong) UIView *subView;
@end
//子视图懒加载
-(UIView *)subView{
    if (_subView == nil) {
        UIView *view = [[UIView alloc] init];
        view.frame = CGRectMake(0, 0, 50, 50);//超出父视图的范围,无法响应点击事件
        view.backgroundColor = [UIColor redColor];
        [self addSubview:view];
        _subView = view;       
    }
    return _subView;
}
  • 当需要对子视图进行重新布局的时候,实现layoutSubViews方法;
  • 当需要做自定义绘图的时候,实现drawRect:方法;下面的代码实现了为视图四周添加一个边框;
-(void)drawRect:(CGRect)rect{
    NSLog(@"%s",__func__);  
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect    myFrame = self.bounds;   
    //添加边框
    CGContextSetLineWidth(context, 10);
    CGRectInset(myFrame, 5, 5);    
    [[UIColor greenColor] set];
    UIRectFrame(myFrame); 
}
  • 如果视图需要响应用户交互,如点击等,可以为视图添加手势或者实现UIResponder类的touches系列方法;
/*配置View点击,作用域在于对象的frame范围内*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"%s 接收到触摸事件",__func__);
} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"%s, event: %@",__func__,event);
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"点击了视图" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];    
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"%s",__func__);
}

-(void)longpressAction {
    NSLog(@"长按了视图");
}

官方文档

https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html#//apple_ref/doc/uid/TP40009503-CH5-SW23

示例代码

https://github.com/99ios/7.2.9