【层级关系】
@interface UIView(UIViewHierarchy)
@property(nonatomic,readonly) UIView *superview;
@property(nonatomic,readonly,copy) NSArray *subviews;//遍历控件用
@property(nonatomic,readonly) UIWindow *window;
NSArray *views = self.view.subviews;
for (NSInteger ii = 0; ii < views.count; ii++) {
if ([[views objectAtIndex:ii] isKindOfClass:[UIButton class]]) {
UIButton *btn = (UIButton *)[views objectAtIndex:ii];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
}
}
【添加,移除,交换层级】
- (void)removeFromSuperview;//移除
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;//在。。位置插入
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;//交换
- (void)addSubview:(UIView *)view;//添加
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;//在。。下面插入
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;//在。。上面插入
- (void)bringSubviewToFront:(UIView *)view;//移到最顶层
- (void)sendSubviewToBack:(UIView *)view;//置于最底层
-(void)soeasy{
<span style="white-space:pre"> </span>NSLog("不写了");
}
【重写已经,将要】
- (void)didAddSubview:(UIView *)subview;//已经添加子视图
- (void)willRemoveSubview:(UIView *)subview;//将要移除子视图
- (void)willMoveToSuperview:(UIView *)newSuperview;//将要添加到父视图
- (void)didMoveToSuperview;//已经添加到父视图
- (void)willMoveToWindow:(UIWindow *)newWindow;//将要展示到屏幕
- (void)didMoveToWindow;//已经展示到屏幕
-(void)didAddSubview:(UIView *)subview{
NSLog(@"3didAddSubview");
}
-(void)willRemoveSubview:(UIView *)subview{
NSLog(@"willRemoveSubview");
}
- (void)willMoveToSuperview:(UIView *)newSuperview{
NSLog(@"1willMoveToSuperview");
}
- (void)didMoveToSuperview{
NSLog(@"2didMoveToSuperview");
}
- (void)willMoveToWindow:(UIWindow *)newWindow{
NSLog(@"4willMoveToWindow");
}
- (void)didMoveToWindow{
NSLog(@"5didMoveToWindow");
}
【判断是否是子视图,tag后去视图】
- (BOOL)isDescendantOfView:(UIView *)view; //判断view是否是自己否控件
greenView = [[UIView alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
greenView.backgroundColor = [UIColor greenColor];
[self.view addSubview:greenView];
if ([greenView isDescendantOfView:self.view]) {
NSLog(@"yes");
}
- (UIView *)viewWithTag:(NSInteger)tag; //通过tag,获取控件
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setFrame:CGRectMake(111, 111, 111, 111)];
button.backgroundColor = [UIColor purpleColor];
button.tag = 1000;
[self.view addSubview:button];
//通过tag 获取UIView,转换成UIButton,
UIButton *btn = (UIButton *)[self.view viewWithTag:1000];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
【自动布局,重新布局】
- (void)setNeedsLayout;//标记需要重新布局
- (void)layoutIfNeeded;//重新布局
- (void)layoutSubviews;// 重新布局
//假设blueView 是通过自动布局,先标记,在布局。
[blueView setNeedsLayout];
[blueView layoutIfNeeded];
@end