iOS纯代码自定义View
- 1.UIGestureRecognizerDelegate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| -(instancetype)init { self = [super init]; if (self) { [self setup]; } return self; }
-(void)setup { self.frame = CGRectMake(0, 0, SIMScreenWidth, SIMScreenHeight); UIColor *color = [UIColor blackColor]; self.backgroundColor = [color colorWithAlphaComponent:0.6]; self.bgView.backgroundColor = [UIColor clearColor];
[self addSubview:self.bgView]; [self.bgView addSubview:self.bgImageView]; [self.bgImageView addSubview:self.topImageView]; [self.bgImageView addSubview:self.textView]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancleButtonClick)]; tap.delegate = self; [self.bgView addGestureRecognizer:tap]; }
|
1 2 3 4
| -(void)layoutSubviews { [super layoutSubviews]; _bgView.frame = CGRectMake(0, 0, SIMScreenWidth, SIMScreenHeight); }
|
1 2 3 4 5 6 7 8
| UIWindow *window = [UIApplication sharedApplication].keyWindow; for (UIView * vc in [window subviews]) { if ([[vc class] isSubclassOfClass:[SIMFDDCommonTipsView class]]) { return; } } [window addSubview:self]; [window makeKeyAndVisible];
|
1 2 3 4 5 6 7 8 9
| - (void)cancleButtonClick { UIWindow *window = [UIApplication sharedApplication].keyWindow; for (UIView * vc in [window subviews]) { if ([[vc class] isSubclassOfClass:[SIMFDDCommonTipsView class]]) { [vc removeFromSuperview]; break; } } }
|
1 2 3 4 5 6
| - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{ if ([touch.view isDescendantOfView:self.bgImageView] || [touch.view isDescendantOfView:self.topImageView]) { return NO; } return YES; }
|
总结一下当我们使用纯代码创建自定义
UIVIew的时候步骤:
1、新建一个继承UIVIew的类;
2、在实现文件中添加子控件(weak声明);
3、重写- (instancetype)initWithFrame:(CGRect)frame初始化子控件但不设置子控件frame;
4、重写- (void)layoutSubviews,设置子控件frame,记得一定要写[super layoutSubviews];
5、提供一个模型属性,在该模型的set方法中为子控件赋值;