您的位置:首页 > 其它

监听view添加到父控件和自己添加子控件

2015-10-26 08:05 253 查看

监听view添加到父控件和从父控件移除

1.首先执行下面的代码,自定义一个redView并将其添加到控制器view,之后再从父控制器的view中移除

// 创建红色view
RedView *redView = [[RedView alloc] init];
redView.frame = self.view.bounds;
// 将红色view添加到控制器view中
[self.view addSubview:redView];
// 创建button
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
// 添加button到红色view中
[redView addSubview:button];
// 从红色view中移除
[button removeFromSuperview];


2.在自定义的类RedView中重写下面的代码

/**
*  即将要添加到父控件
*/
- (void)willMoveToSuperview:(UIView *)newSuperview;
{
NSLog(@"%s", __func__);
}
/**
*  已经添加到父控件
*/
- (void)didMoveToSuperview
{
NSLog(@"%s", __func__);
}
/**
*  即将添加子控件
*/
- (void)didAddSubview:(UIView *)subview
{
NSLog(@"%s", __func__);
}
/**
*  子控件将从自己subviews数组中移除
*/
- (void)willRemoveSubview:(UIView *)subview;
{
NSLog(@"%s", __func__);
}
````


3.发现在执行1中的代码的时候,会依次打印2中的代码的方法

总结:可以重写2中的代码监听控件添加子控件,移除子控件,并在需要的时候做些事情

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  控件 view