自定义伸缩控件rootview,内部包含4个子view,位于4个角落
layoutSubviews系统方法用于重新布局时调用;
头文件
#import <UIKit/UIKit.h>
@interface RootView : UIView{
UIView* view1;
UIView* view2;
UIView* view3;
UIView* view4;
}
-(void) createSubViews;
@end
源文件
#import "RootView.h"
@implementation RootView
-(void) createSubViews{
view1 = [[UIView alloc]init];
view1.frame = CGRectMake(0, 0, 50, 50);
view1.backgroundColor = [UIColor greenColor];
view2 = [[UIView alloc]init];
view2.frame = CGRectMake(self.bounds.size.width - 50, 0, 50, 50);
view2.backgroundColor = [UIColor yellowColor];
view3 = [[UIView alloc]init];
view3.frame = CGRectMake(0, self.bounds.size.height - 50, 50, 50);
view3.backgroundColor = [UIColor redColor];
view4 = [[UIView alloc]init];
view4.frame = CGRectMake(self.bounds.size.width-50, self.bounds.size.height-50, 50, 50);
view4.backgroundColor = [UIColor grayColor];
[self addSubview:view1];
[self addSubview:view2];
[self addSubview:view3];
[self addSubview:view4];
}
-(void) layoutSubviews{
view1.frame = CGRectMake(0, 0, 50, 50);
view2.frame = CGRectMake(self.bounds.size.width - 50, 0, 50, 50);
view3.frame = CGRectMake(0, self.bounds.size.height - 50, 50, 50);
view4.frame = CGRectMake(self.bounds.size.width-50, self.bounds.size.height-50, 50, 50);
}
@end
编写页面布局ViewController
头文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
源文件
#import "ViewController.h"
#import "RootView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initView];
}
-(void) initView{
RootView* root = [[RootView alloc]init];
root.frame = CGRectMake(20, 20, 200, 200);
root.backgroundColor = [UIColor orangeColor];
[self.view addSubview:root];
[root createSubViews];
UIButton* btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn1.frame = CGRectMake(20, 500, 200, 50);
[btn1 setTitle:@"放大" forState:UIControlStateNormal];
[btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn1.backgroundColor = [UIColor grayColor];
[self.view addSubview:btn1];
UIButton* btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn2.frame = CGRectMake(20, 580, 200, 50);
[btn2 setTitle:@"缩小" forState:UIControlStateNormal];
[btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn2.backgroundColor = [UIColor grayColor];
[self.view addSubview:btn2];
[btn1 addTarget:self action:@selector(larger) forControlEvents:UIControlEventTouchUpInside];
[btn2 addTarget:self action:@selector(small) forControlEvents:UIControlEventTouchUpInside];
root.tag = 101;
}
-(void) larger{
RootView* root = [self.view viewWithTag:101];
root.frame = CGRectMake(20, 20, 300, 300);
}
-(void) small{
RootView* root = [self.view viewWithTag:101];
root.frame = CGRectMake(20, 20, 200, 200);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论